Sunday, February 26, 2017

Perl Moving Average Beispiel

Dieses Kapitel stellt Ihnen die Konzepte hinter Referenzen zu Perl-Modulen, Paketen und Klassen vor. Es zeigt auch, wie Sie ein paar Beispiel-Module zu erstellen. Ein Perl-Modul ist ein Satz von Perl-Code, der wie eine Bibliothek von Funktionsaufrufen wirkt. Der Begriff Modul in Perl ist gleichbedeutend mit dem Wortpaket. Pakete sind ein Merkmal von Perl 4, während Module in Perl 5 vorherrschen. Sie können alle Ihren wiederverwendbaren Perl-Code für eine Reihe von Aufgaben in einem Perl-Modul zu halten. Daher ist die gesamte Funktionalität eines Task-Typs in einer Datei enthalten. Es ist einfacher, eine Anwendung auf diese modularen Blöcke zu bauen. Daher gilt das Wort-Modul ein wenig mehr als Paket. Heres eine kurze Einführung in Module. Bestimmte Themen in diesem Abschnitt werden im Detail in den Rest des Buches behandelt werden. Lesen Sie die folgenden Abschnitte sorgfältig durch, um einen Überblick darüber zu erhalten, was vor Ihnen liegt, wenn Sie Ihre eigenen Module schreiben und verwenden. Was ist verwirrend ist, dass die Begriffe Modul und Paket austauschbar in allen Perl-Dokumentation verwendet werden, und diese beiden Begriffe bedeuten die gleiche Sache. Also, wenn Sie Perl-Dokumente lesen, einfach thinkpackagequot, wenn Sie sehen, quotmodulequot und umgekehrt. Also, was ist die Voraussetzung für die Verwendung von Modulen Nun, Module gibt es zu verpacken (verzeihen die Wortspiel) Variablen, Symbole und miteinander verbundene Datenelemente zusammen. Zum Beispiel, mit globalen Variablen mit sehr häufigen Namen wie k. J Oder i in einem Programm ist in der Regel keine gute Idee. Auch ein Schleifenzähler, d. h. Sollte es erlaubt sein, selbstständig in zwei verschiedenen Teilen des Codes zu arbeiten. Das Deklarieren von i als globale Variable und dann das Inkrementieren aus einer Subroutine wird unhandhabbare Probleme mit Ihrem Anwendungscode verursachen, da die Subroutine aus einer Schleife heraus aufgerufen worden sein könnte, die auch eine Variable namens i nutzt. Durch die Verwendung von Modulen in Perl können Variablen mit demselben Namen an verschiedenen, unterschiedlichen Orten im selben Programm erstellt werden. Die für Ihre Variablen definierten Symbole werden in einem assoziativen Array gespeichert, das als Symboltabelle bezeichnet wird. Diese Symboltabellen sind für ein Paket eindeutig. Daher können Variablen mit demselben Namen in zwei verschiedenen Paketen unterschiedliche Werte haben. Jedes Modul hat seine eigene Symboltabelle aller Symbole, die in ihm deklariert sind. Die Symboltabelle isoliert grundsätzlich auch Namen in einem Modul von einem anderen. Die Symboltabelle definiert einen Namensraum. Dh ein Raum für unabhängige Variablennamen, der existiert. Somit verhindert die Verwendung von Modulen mit jeweils einer eigenen Symboltabelle, dass eine in einem Abschnitt deklarierte Variable die Werte anderer Variablen mit demselben Namen überschreibt, die an anderer Stelle deklariert sind Programm. In der Tat, alle Variablen in Perl gehören zu einem Paket. Die Variablen in einem Perl-Programm gehören zum Hauptpaket. Alle anderen Pakete innerhalb eines Perl-Programms sind entweder innerhalb dieses Hauptpakets verschachtelt oder befinden sich auf derselben Ebene. Es gibt einige wirklich globale Variablen, wie das Signalhandler-Array SIG. Die allen anderen Modulen in einem Anwendungsprogramm zur Verfügung stehen und nicht über Namensräume isoliert werden können. Nur diejenigen Variablen, die mit Buchstaben oder einem Unterstrich beginnen, werden in einer Modul-Symboltabelle aufbewahrt. Alle anderen Symbole, wie die Namen STDIN. STDOUT. STDERR. ARGV. ARGVOUT. ENV. Inc. Und SIG werden gezwungen, in der Pakethauptleitung zu sein. Das Umschalten zwischen Paketen betrifft nur Namespaces. Alles, was Sie tun, wenn Sie ein Paket oder ein anderes verwenden ist die Erklärung, welche Symboltabelle als Standard-Symbol-Tabelle für die Suche nach Variablennamen zu verwenden. Nur dynamische Variablen werden durch die Verwendung von Symboltabellen beeinflusst. Variablen, die durch die Verwendung des Schlüsselworts deklariert werden, werden immer noch mit dem Codeblock behoben, in dem sie sich befinden, und werden nicht durch Symboltabellen referenziert. Tatsächlich bleibt der Gültigkeitsbereich einer Paketdeklaration nur innerhalb des Codeblocks aktiv, in dem es deklariert ist. Wenn Sie also Symboltabellen unter Verwendung eines Pakets in einer Subroutine umschalten, wird die ursprüngliche Symboltabelle, die beim Aufruf des Aufrufs wirksam ist, wiederhergestellt Wenn das Unterprogramm zurückkehrt. Das Schalten von Symboltabellen wirkt sich nur auf die standardmäßige Suche nach dynamischen Variablennamen aus. Sie können weiterhin explizit auf Variablen, Dateihandles und so weiter in einem bestimmten Paket verweisen, indem Sie ein packageName voranstellen. Auf den Variablennamen. Sie haben gesehen, was ein Paketkontext bei der Verwendung von Referenzen in Kapitel 3 war. Ein Paketkontext impliziert die Verwendung der Symboltabelle durch den Perl-Interpreter zum Auflösen von Variablennamen in einem Programm. Durch das Umschalten von Symboltabellen wechseln Sie den Paketkontext. Module können in andere Module geschachtelt werden. Das verschachtelte Modul kann die Variablen und Funktionen des Moduls verwenden, in dem es verschachtelt ist. Für verschachtelte Module müssten Sie moduleName verwenden. NestedModuleName und so weiter. Mit dem Doppel-Doppelpunkt (::) ist auch mit einem Back-Anführungszeichen (). Der Doppelkolon ist jedoch die bevorzugte, zukünftige Möglichkeit, Variablen innerhalb von Modulen zu adressieren. Die explizite Adressierung der Modulvariablen erfolgt immer mit einer vollständigen Referenz. Angenommen, Sie haben ein Modul, Investment. Das das verwendete Standardpaket ist, und Sie möchten ein anderes Modul, Bonds, adressieren. Die innerhalb des Investitionsmoduls verschachtelt ist. In diesem Fall können Sie Bond :: nicht verwenden. Stattdessen müssten Sie Investment :: Bond :: verwenden, um Variablen und Funktionen innerhalb des Bond-Moduls ansprechen zu können. Die Verwendung von Bond :: würde die Verwendung eines Package Bond implizieren, das innerhalb des Hauptmoduls und nicht innerhalb des Investment-Moduls verschachtelt ist. Die Symboltabelle für ein Modul wird tatsächlich in einem assoziativen Array der Modulnamen gespeichert, die mit zwei Doppelpunkten angehängt sind. Die Symboltabelle für ein Modul namens Bond wird als assoziatives Array Bond :: bezeichnet. Der Name für die Symboltabelle für das Hauptmodul ist main ::. Und kann sogar verkürzt werden auf ::. In ähnlicher Weise haben alle verschachtelten Pakete ihre Symbole in assoziativen Arrays gespeichert, wobei doppelte Doppelpunkte jede Schachtelungsebene trennen. Zum Beispiel wird im Bond-Modul, das innerhalb des Investment-Moduls verschachtelt ist, das assoziative Array für die Symbole im Bond-Modul mit dem Namen Investment :: Bond :: bezeichnet. Ein Typglob ist wirklich ein globaler Typ für einen Symbolnamen. Sie können Aliasing-Operationen durch Zuweisung zu einem Typglob durchführen. Ein oder mehrere Einträge in einem assoziativen Array für Symbole werden verwendet, wenn eine Zuweisung über einen Typglob verwendet wird. Der tatsächliche Wert in jedem Eintrag des assoziativen Arrays ist, was Sie beziehen sich auf, wenn Sie die variableName Notation verwenden. Somit gibt es zwei Möglichkeiten, auf Variablennamen in einem Paket zu verweisen: Investment :: money Investment :: Rechnungen In der ersten Methode beziehen Sie sich auf die Variablen über einen Typglob-Verweis. Die Verwendung der Symboltabelle, Investment ::. Ist impliziert, und Perl optimiert die Suche nach Symbolen Geld und Rechnungen. Dies ist die schnellere und bevorzugte Art, ein Symbol zu adressieren. Die zweite Methode verwendet eine Suche nach dem Wert einer Variablen, die von Geld und Rechnungen im assoziativen Array für Symbole, Investment :: explizit verwendet adressiert wird. Diese Suche wäre dynamisch und wird nicht von Perl optimiert werden. Daher wird die Suche gezwungen, das assoziative Array jedes Mal zu überprüfen, wenn die Anweisung ausgeführt wird. Infolgedessen ist das zweite Verfahren nicht effizient und sollte nur zur Demonstration verwendet werden, wie die Symboltabelle intern implementiert wird. Ein weiteres Beispiel in dieser Anweisung kamran husain verursacht Variablen, Subroutinen und Dateihandles, die über das Symbol kamran benannt werden, um auch über das Symbol husain angesprochen zu werden. Das heißt, alle Symboleinträge in der aktuellen Symboltabelle mit dem Schlüssel kamran enthalten nun Verweise auf die Symbole, die von dem Schlüssel husain adressiert werden. Um eine solche globale Zuordnung zu verhindern, können Sie explizite Verweise verwenden. Mit der folgenden Anweisung können Sie beispielsweise den Inhalt von husain über die Variable kamran ansprechen. Kamran husain Allerdings werden alle Arrays wie kamran und husain nicht die gleichen sein. Nur die explizit angegebenen Referenzen werden geändert. Zusammenfassend beeinflussen Sie, wenn Sie einem Typglob einem anderen zuweisen, alle Einträge in einer Symboltabelle unabhängig vom Typ der Variablen, auf die verwiesen wird. Wenn Sie eine Referenz von einem Variablentyp zu einem anderen zuordnen, wirkt sich dies nur auf einen Eintrag in der Symboltabelle aus. Eine Perl-Moduldatei hat das folgende Format: package ModuleName. Modulcode einfügen. 1 Der Dateiname muss als ModuleName. pm aufgerufen werden. Der Name eines Moduls muss in der Zeichenfolge. pm nach Konvention enden. Die Paketanweisung ist die erste Zeile der Datei. Die letzte Zeile der Datei muss die Zeile mit der Anweisung 1 enthalten. Das gibt mit dem Modul einen wahren Wert an das Anwendungsprogramm zurück. Durch die Verwendung der Anweisung 1 wird das Modul nicht korrekt geladen. Die Paketanweisung weist den Perl-Interpreter an, mit einer neuen Namespace-Domäne zu beginnen. Grundsätzlich gehören alle Ihre Variablen in einem Perl-Skript zu einem Paket namens main. Jede Variable im Hauptpaket kann als mainvariable bezeichnet werden. Heres die Syntax für solche Verweise: packageNamevariableName Die einzige Anführungszeichen () ist gleichbedeutend mit dem Doppel-Doppelpunkt (::) - Operator. Ich decke im nächsten Kapitel weitere Verwendungen des Operators "::" ab. Vorerst müssen Sie sich daran erinnern, dass die folgenden zwei Anweisungen gleich sind: packageNamevariableName packageName :: variableName Die Doppel-Colon-Syntax gilt als Standard in der Perl-Welt. Deshalb, um Lesbarkeit zu bewahren, verwende ich die Doppel-Kolon-Syntax im Rest dieses Buches, es sei denn, es ist absolut notwendig, Ausnahmen zu machen, um einen Punkt zu beweisen. Die Standardeinstellung eines Variablennamens verweist auf das aktuelle Paket, das zum Zeitpunkt der Kompilierung aktiv ist. Also, wenn Sie im Paket Finance. pm sind und geben Sie eine Variable pv. Die Variable ist tatsächlich gleich Finance :: pv. Verwenden von Perl-Modulen: Verwendung vs. require Sie enthalten Perl-Module in Ihrem Programm, indem Sie die use - oder die require-Anweisung verwenden. Hier ist die Möglichkeit, eine dieser Anweisungen zu verwenden: use ModuleName require ModuleName Beachten Sie, dass die Erweiterung. pm nicht in dem oben gezeigten Code verwendet wird. Beachten Sie auch, dass keine Anweisung erlaubt, eine Datei mehr als einmal in einem Programm aufgenommen werden. Der zurückgegebene Wert von true (1) als letzte Anweisung ist erforderlich, damit Perl weiß, dass ein d erforderlich ist oder d-Modul korrekt geladen ist, und lässt den Perl-Interpreter keine Neuladen ignorieren. Im Allgemeinen ist es besser, die Verwendung von Modul-Anweisung als die erfordern Module-Anweisung in einem Perl-Programm verwenden, um kompatibel mit zukünftigen Versionen von Perl bleiben. Für Module sollten Sie die fortwährende Verwendung der require-Anweisung in Erwägung ziehen. Heres why: Die use-Anweisung hat ein wenig mehr Arbeit als die require-Anweisung, da sie den Namespace des Moduls, das ein anderes Modul enthält, verändert. Sie möchten, dass dieses zusätzliche Update des Namespaces in einem Programm durchgeführt wird. Wenn Sie jedoch Code für ein Modul schreiben, dürfen Sie den Namensraum nicht ändern, wenn er nicht explizit erforderlich ist. In diesem Fall verwenden Sie die require-Anweisung. Die require-Anweisung enthält den vollständigen Pfadnamen einer Datei im Inc-Array, sodass sich die Funktionen und Variablen in der modules-Datei an einem bekannten Ort während der Ausführungszeit befinden. Daher werden die Funktionen, die aus einem Modul importiert werden, über eine explizite Modulreferenz zur Laufzeit mit der require-Anweisung importiert. Die use-Anweisung macht dasselbe wie die require-Anweisung, da sie das Inc-Array mit vollständigen Pfadnamen geladener Module aktualisiert. Der Code für die use - Funktion geht ebenfalls einen Schritt weiter und ruft im Modul d eine Importfunktion auf, mit der explizit die Liste der exportierten Funktionen zur Kompilierzeit geladen wird, wodurch die für die explizite Auflösung eines Funktionsnamens während der Ausführung erforderliche Zeit gespart wird. Grundsätzlich ist die use-Anweisung gleichbedeutend mit ModulName import ModulName Liste der importierten Funktionen Die Verwendung der use-Anweisung ändert den Namensraum Ihrer Programme, weil die importierten Funktionsnamen in die Symboltabelle eingefügt werden. Die require-Anweisung ändert Ihren Programm-Namespace nicht. Daher ist die folgende Anweisung verwenden ModuleName () entspricht dieser Anweisung: require ModuleName Funktionen werden aus einem Modul über einen Aufruf einer Funktion importiert importiert importiert. Sie können Ihre eigene Importfunktion in einem Modul schreiben oder das Exporter-Modul verwenden und dessen Importfunktion nutzen. In fast allen Fällen verwenden Sie das Exporter-Modul, um eine Importfunktion zu bieten, anstatt das Rad neu zu erfinden. (Youll erfahren Sie mehr hierzu im nächsten Abschnitt.) Sollten Sie sich entschließen, das Exporter-Modul nicht zu verwenden, müssen Sie in jedem Modul, das Sie schreiben, eine eigene Importfunktion schreiben. Es ist viel einfacher, einfach das Exporter-Modul verwenden und lassen Perl die Arbeit für Sie erledigen. Das Sample Letter. pm Modul Am besten veranschaulichen wir die Semantik, wie ein Modul in Perl verwendet wird, um ein einfaches Modul zu schreiben und zu zeigen, wie man es benutzt. Nehmen wir das Beispiel eines lokalen Darlehen Hai, Rudious Maximus, die einfach müde von der Eingabe der gleiche quotququest für paymentquot Briefe ist. Als begeisterter Fan von Computern und Perl, nimmt Rudious die faule Programmierer Ansatz und schreibt ein Perl-Modul, um ihm zu helfen, seine Memos und Briefe generieren. Nun, anstatt, Felder innerhalb einer Memo-Vorlagendatei zu schreiben, muss er nur ein paar Zeilen eingeben, um seine schöne, drohende Note zu erzeugen. Listing 4.1 zeigt Ihnen, was er eingeben muss. Listing 4.1. Verwenden des Briefmoduls. 1 usrbinperl - w 2 3 Deaktivieren Sie die Zeile unten, um das aktuelle Verzeichnis in Inc. einzufügen 4 push (Inc, pwd) 5 6 use Letter 7 8 Letter :: To (quotMr. Gambling Manquot, quotDas Geld für Lucky Dog, Race 2quot) 9 Letter :: ClaimMoneyNice () 10 Letter :: ThankDem () 11 Letter :: Finish () Die Letter-Anweisung ist vorhanden, um den Perl-Interpreter zu zwingen, den Code für das Modul im Anwendungsprogramm aufzunehmen. Das Modul sollte sich im Verzeichnis usrlibperl5 befinden, oder Sie können es in jedes Verzeichnis, das im Inc-Array aufgelistet ist, platzieren. Das Inc-Array ist die Liste der Verzeichnisse, die der Perl-Interpreter sucht, wenn er versucht, den Code für das benannte Modul zu laden. Die kommentierte Zeile (Nummer 4) zeigt, wie das aktuelle Arbeitsverzeichnis hinzugefügt werden soll, um den Pfad einzuschließen. Die nächsten vier Zeilen in der Datei erzeugen den Inhalt für den Buchstaben. Heres die Ausgabe von der Verwendung der Brief-Modul: An: Mr. Gambling Man Fm: Rudious Maximus, Darlehen Shark Dt: Wed Feb 7 10:35:51 CST 1996 Re: Das Geld für Lucky Dog, Race 2 Es ist mir aufgefallen Dass Ihr Konto ist über fällig. Sie gonna zahlen uns bald Oder möchten Sie, dass ich ovah Dank für Ihre Unterstützung komme. Die Letter-Moduldatei ist in Listing 4.2 dargestellt. Der Name des Pakets wird in der ersten Zeile deklariert. Da diese Module Funktionen exportiert werden, verwende ich das Exporter-Modul. Daher ist die Anweisung Verwendung Exporter erforderlich, um Funktionalität aus dem Exporter-Modul erben. Ein weiterer erforderlicher Schritt besteht darin, das in das ISA-Array exportierte Wort zu exportieren. Das ISA-Array ist ein spezielles Array in jedem Paket. Jedes Element in dem Array listet, wo sonst nach einer Methode zu suchen, wenn es nicht im aktuellen Paket gefunden werden kann. Die Reihenfolge, in der Pakete im ISA-Array aufgelistet werden, ist die Reihenfolge, in der Perl nach ungelösten Symbolen sucht. Eine Klasse, die im ISA-Array aufgelistet wird, wird als Basisklasse dieser Klasse bezeichnet. Perl cache fehlende Methoden, die in Basisklassen für zukünftige Verweise gefunden werden. Das Ändern des ISA-Arrays wird den Cache bündeln und Perl dazu veranlassen, alle Methoden erneut aufzurufen. Schauen wir uns nun den Code für Letter. pm in Listing 4.2 an. Listing 4.2. Das Modul Letter. pm. 1 Paket Brief 2 3 erfordern Exporteur 4 ISA (Exporteur) 5 6 head1 NAME 7 8 Letter - Beispielmodul zur Erstellung von Briefkopf für Sie 9 10 head1 SYNOPSIS 11 12 use Letter 13 14 Letter :: Date () 15 Letter :: To (name , Firma, Anschrift) 16 17 Dann eine der folgenden: 18 Buchstabe :: ClaimMoneyNice () 19 Buchstabe :: ClaimMoney () 20 Buchstabe :: ThreatBreakLeg () 21 22 Buchstabe :: ThankDem () 23 Buchstabe :: Finish () 24 25 head1 BESCHREIBUNG 26 27 Dieses Modul stellt ein kurzes Beispiel für die Erstellung eines Briefes für einen 28 freundlichen Nachbarburthard dar. 29 30 Der Code beginnt nach der quotcutquot-Anweisung. 31 Ausschneiden 32 33 EXPORT qw (Datum, 34 Bis, 35 ClaimMoney, 36 ClaimMoneyNice, 37 ThankDem, 38 Finish) 39 40 41 Drucken heutigen Datum 42 43 sub Buchstabe :: Datum 44 Datum Datum 45 print quotn Heute ist datequot 46 47 48 sub Buchstabe :: Zu 49 lokaler (Name) Verschiebung 50 lokaler (Subjekt-) Verschiebung 51 print quotn An: namequot 52 print quotn Fm: Rudious Maximus, Darlehen Sharkquot 53 print quotn Dt: quot, date 54 print quotn Re: subjectquot 55 print quotnnquot 56 Print quotnnquot 57 58 sub Letter :: ClaimMoney () 59 print quotn Sie schulden mir Geld. Holen Sie sich Ihre Akt-togetherquot 60 print quotn Wollen Sie, dass ich Bruno zu schicken auf 61 drucken quotn sammeln. Oder sind Sie gonna zahlen upquot 62 63 64 sub Letter :: ClaimMoneyNice () 65 print quotn Es ist zu meiner Aufmerksamkeit, dass Ihr Konto ist 66 print quotn Weg über due. quot 67 print quotn Sie gonna bezahlen uns bald .. quot 68 Print quotn oder möchten Sie mir zu kommen ovahquot 69 70 71 sub Letter :: ThreatBreakLeg () 72 drucken quotn scheinbar Briefe wie diese nicht helpquot 73 print quotn Ich muss ein Beispiel für youquot 74 print quotn n sehen Sie im Krankenhaus , Palquot 75 76 77 Letter :: ThankDem () 78 print quotnn Vielen Dank für Ihr supportquot 79 80 81 sub Letter :: Finish () 82 printf quotnnnn Sincerelyquot 83 printf quotn Rudious n 84 85 86 1 Zeilen mit dem Gleichheitszeichen werden verwendet Für die Dokumentation. Sie müssen jedes Modul für Ihre eigene Referenz zu dokumentieren Perl-Module müssen nicht dokumentiert werden, aber es ist eine gute Idee, ein paar Zeilen über das, was Ihr Code tut, zu schreiben. Ein paar Jahre, können Sie vergessen, was ein Modul über ist. Gute Dokumentation ist immer ein Muss, wenn Sie sich erinnern, was Sie haben in der Vergangenheit Ich decken Dokumentationsstile für Perl in Kapitel 8 verwendet. QuotDocumenting Perl Scripts. quot Für dieses Beispiel-Modul beginnt die head1-Anweisung die Dokumentation. Alles bis zu der cut-Anweisung wird vom Perl-Interpreter ignoriert. Als Nächstes listet das Modul alle Funktionen auf, die von diesem Modul im EXPORT-Array exportiert werden. Das EXPORT-Array definiert alle Funktionsnamen, die von externem Code aufgerufen werden können. Wenn Sie keine Funktion in diesem EXPORT-Array auflisten, wird es nicht von externen Code-Modulen angezeigt. Nach dem EXPORT-Array ist der Körper des Codes, eine Unterroutine zu einem Zeitpunkt. Nachdem alle Subroutinen definiert sind, beendet die letzte Anweisung 1 die Moduldatei. 1 muss die letzte ausführbare Zeile in der Datei sein. Hier sehen Sie einige der in diesem Modul definierten Funktionen. Die erste Funktion ist die einfache Date-Funktion, Zeilen 43 bis 46, die das aktuelle UNIX-Datum und die aktuelle Zeit ausgibt. Es gibt keine Parameter für diese Funktion, und es gibt keine sinnvolle zurück an den Anrufer. Beachten Sie die Verwendung meiner vor der Datumsvariablen in Zeile 44. Das Keyword wird verwendet, um den Bereich der Variable innerhalb der Date-Funktionen geschweifte Klammern zu begrenzen. Code zwischen geschweiften Klammern wird als Block bezeichnet. Variablen, die innerhalb eines Blocks deklariert werden, sind auf den Bereich innerhalb der geschweiften Klammern beschränkt. In 49 und 50 sind die lokalen Variablen Name und Betreff für alle Funktionen sichtbar. Sie können auch Variablen mit dem lokalen Qualifier deklarieren. Die Verwendung von local ermöglicht es, dass eine Variable sowohl für den aktuellen Block als auch für andere Codeblöcke innerhalb dieses Blocks aufgerufen wird. Somit ist ein lokales x, das innerhalb eines Blocks deklariert ist, für alle nachfolgenden Blöcke sichtbar, die von diesem Block aufgerufen werden und auf die verwiesen werden kann. Im folgenden Beispielcode kann auf die ToTitled-Funktionsnamenvariable zugegriffen werden, jedoch nicht auf die Daten im iPhone. 1 sub Letter :: ToTitled 2 local (name) shift 3 my (phone) shift Der Beispielcode für Letter. pm zeigt, wie Sie einen Parameter zu einem Zeitpunkt extrahieren können. Die Unterroutine To () verwendet zwei Parameter, um den Header für das Memo einzurichten. Die Verwendung von Funktionen innerhalb eines Moduls unterscheidet sich nicht von der Verwendung und Definition von Perl-Modulen innerhalb derselben Codedatei. Die Parameter werden als Referenz übergeben, sofern nicht anders angegeben. Mehrere Arrays, die in eine Subroutine übergeben werden, wenn sie nicht explizit mit dem Backslash disereferenziert werden, werden verkettet. Das Eingabearray in einer Funktion ist immer ein Array von Skalarwerten. Das Übergeben von Werten durch Verweis ist der bevorzugte Weg in Perl, um eine große Menge an Daten in eine Unterroutine zu übergeben. (Siehe Kapitel 3. quotReferences. quot) Ein weiteres Beispielmodul: Finanzen Das in Listing 4.3 dargestellte Modul Finance wird für einfache Berechnungen von Kreditwerten verwendet. Die Verwendung des Finanzmoduls ist einfach. Alle Funktionen werden mit den gleichen Parametern wie in der Formel für die Funktionen beschrieben geschrieben. Schauen wir uns, wie der zukünftige Wert einer Anlage berechnet werden kann. Zum Beispiel, wenn Sie investieren einige Dollar, pv. In einer Anleihe mit einem festen Prozentsatz, r. Die in Zeitintervallen mit bekannten Intervallen angewendet werden, was der Wert der Bindung zum Zeitpunkt des Ablaufs ist In diesem Fall verwenden Sie die folgende Formel: fv pv (1r) n Die Funktion, um den zukünftigen Wert zu erhalten, wird als FutureValue deklariert . Siehe Listing 4.3, um zu sehen, wie man es benutzt. Listing 4.3. Verwenden des Finanzmoduls. 1 usrbinperl - w 2 3 push (Inc, pwd) 4 Nutzung Finanzen 5 6 Darlehen 5000,00 7 Apr 3,5 APR 8 Jahre 10 Jahre. 9 10 ------------------------------------------------- ---------------- 11 Berechnen Sie den Wert am Ende des Darlehens, wenn Zinsen 12 jedes Jahr angewendet wird. 13 ------------------------------------------------- --------------- 14 Zeitjahr 15 fv1 Finanzen :: FutureValue (Darlehen, apr, Zeit) 16 print quotn Wird am Ende des Jahresquotienten verzinst 17 print quotn Der zukünftige Wert für a Darlehen von quot. Darlehen. Quotquot 18 print quot zu einem APR von quot, apr. Für quot, time, quot yearsquot 19 printf quot ist 8.2f nquot. Fv1 20 21 ----------------------------------------------- ----------------- 22 Berechnen Sie den Wert am Ende des Darlehens, wenn Zins 23 jeden Monat angewendet wird. 24 ------------------------------------------------- --------------- 25 Rate April 12 APR 26 Zeit Jahr 12 in Monaten 27 fv2 Finanzen :: FutureValue (Darlehen, Raten, Zeit) 28 29 print quotn Wenn Zinsen am Ende angewendet werden Jeder monthquot 30 print quotn Der zukünftige Wert für ein Darlehen von quot. Darlehen. Quotquot 31 print quot zu einem APR von quot, apr. Für quot, time, quot monthquot 32 printf quot ist 8.2f nquot. Fv2 33 34 printf quotn Die Differenz im Wert ist 8.2fquot, fv2 - fv1 35 printf quotn Daher durch die Anwendung von Zinsen bei kürzeren Zeitperiodenquot 36 printf quotn wir sind eigentlich immer mehr Geld in interest. nquot Hier ist Beispiel Eingabe und Ausgabe von Listing 4.3. Testme Wenn Zinsen am Ende des Jahres angewendet werden Der zukünftige Wert für ein Darlehen von 5000 bei einem APR von 3,5 für 10 Jahre ist 7052,99 Wenn Zinsen am Ende eines jeden Monats angewendet werden Der zukünftige Wert für ein Darlehen von 5000 bei einem APR von 3,5 für 120 Monate beträgt 7091,72 Der Unterschied im Wert ist 38,73 Daher durch die Anwendung von Zinsen in kürzeren Zeiträumen sind wir tatsächlich mehr Geld im Interesse. Die Offenbarung im Ausgang ist das Ergebnis des Vergleichs der Werte zwischen fv1 und fv2. Der fv1-Wert wird mit der Anwendung von Zinsen einmal jährlich über die Laufzeit der Anleihe berechnet. Fv2 ist der Wert, wenn die Zinsen jeden Monat zum entsprechenden monatlichen Zinssatz angewendet werden. Das Finance. pm-Paket wird in Listing 4.4 in seiner frühen Entwicklungsphase gezeigt. Listing 4.4. Das Finanz. pm-Paket. 1 Paket Finanzierung 2 3 erfordern Exporteur 4 ISA (Exporteur) 5 6 head1 Finanzen. pm 7 8 Finanzrechner - Finanzrechnungen leicht gemacht mit Perl 9 10 Kopf 2 11 Nutzung Finanzen 12 13 pv 10000.0 14 15 Rate 12,5 12 APR pro Monat. 16 17 Zeit 360 Monate für die Refinanzierung 18 19 fv FutureValue () 20 21 Druck fv 22 23 Schnitt 24 25 EXPORT qw (FutureValue, 26 PresentValue, 27 FVofAnnuity, 28 AnnuityOfFV, 29 getLastAverage, 30 getMovingAverage, 31 SetInterest) 32 33 34 Globals, falls vorhanden 35 36 37 lokales defaultInterest 5.0 38 39 sub Finanzen :: SetInterest () 40 meine rate shift () 41 defaultInterestrate 42 printf quotn defaultInterest ratequot 43 44 45 -------------- -------------------------------------------------- ---- 46 Anmerkungen: 47 1. Der Zinssatz r wird in einem Wert von 0-100 angegeben. 48 2. In den Konditionen ist der Zinssatz der Zins 49 anzugeben. 50 51 ------------------------------------------------- -------------------- 52 53 ----------------------------- ---------------------------------------- 54 Barwert einer investierten Anlage 55 fv - Ein zukünftiger Wert 56 r - Satz pro Periode 57 n - Zeitraum 58 ---------------------------------- ---------------------------------- 59 Unterfinanzierung :: FutureValue () 60 my (pv, r, n ) 61 mein fv pv ((1 (r100)) n) 62 Rückkehr fv 63 64 65 ------------------------------ -------------------------------------- 66 Gegenwartswert einer investierten Anlage 67 fv - eine Zukunft Wert 68 r - Satz pro Periode 69 n - Anzahl der Periode 70 ------------------------------------ -------------------------------- 71 sub Finanzen :: PresentValue () 72 meine pv 73 meine (fv, r, N) 74 pv fv ((1 (r100)) n) 75 Rückkehr pv 76 77 78 79 ----------------------------- --------------------------------------- 80 Holen Sie sich die Zukunft Wert einer Annuität gegeben 81 mp - Monatliche Rentenzahlung 82 r - Satz pro Periode 83 n - Anzahl der Perioden 84 -------------------------------- ------------------------------------ 85 86 sub FVofAnnuity () 87 meine fv 88 meine oneR 89 meine (Mp, r, n) 90 91 einR (1 r) n 92 fv mp ((oneR - 1) r) 93 Rückkehr fv 94 95 96 ------------------ -------------------------------------------------- 97 Holen Sie sich die Annuität aus den folgenden Bits 98 r - Rate pro Periode 99 n - Anzahl der Perioden 100 fv - Future Value 101 ---------------------- -------------------------------------------- 102 103 sub AnnuityOfFV (104) mp fv (r (oneR - 1)) 110 Rückkehr mp 111 112 113 - - - - - - - - - - - - - - - - - - - -------------------------------------------------- ---------------- 114 Den Mittelwert der letzten Quotientenwerte in einem Array erhalten. 115 ------------------------------------------------- ------------------- 116 Die letzte Anzahl von Elementen aus dem Array in Werten 117 Die Gesamtzahl der Elemente in Werten ist in der Zahl 118 119 sub getLastAverage () 120 my (Anzahl, Werte) 121 my i 122 123 my a 0 124 return 0 if (count 0) 125 für (i 0 ilt count i) 126 a Wertezahl - i - 1 127 128 Anzahl zurückzählen 129 130 131 --- -------------------------------------------------- --------------- 132 Einen gleitenden Durchschnitt der Werte erhalten. 133 ------------------------------------------------- ------------------- 134 Die Fenstergröße ist der erste Parameter, die Anzahl der Elemente im 135 übergebenen Array ist die nächste. (Dies kann innerhalb der 136-Funktion mit der Funktion scalar () leicht berechnet werden, aber die hier gezeigte Subroutine 137 dient auch zur Veranschaulichung der Übergabe von Zeigern.) Der Verweis auf das 138-Array von Werten wird als nächstes übergeben Bezug auf die Stelle 139 sollen die Rückgabewerte gespeichert werden. V 146 147 return 0 if (Zählung 0) 148 return -1 if (count gt number) 149 Rückgabewert: 2 if (count lt 2) 150 151 movingAve0 0 152 movingAvenumber - 1 0 153 für (i0 iltcounti) 154 v Werte 155 av zählen 156 movingAvei 0 157 158 für (icount iltnumberi) 159 v valuesi 160 av zählen 161 v valuesi - count - 1 162 a - v Zähler 163 movingAvei a 164 165 return 0 166 167 168 1 Betrachten Sie die Deklaration der Funktion FutureValue mit (). Die drei Dollarzeichen zusammen bedeuten drei skalare Zahlen, die in die Funktion übergeben werden. Dieses zusätzliche Scoping ist vorhanden, um den Typ der Parameter zu validieren, die in die Funktion übergeben werden. Wenn Sie eine Zeichenfolge anstelle einer Zahl in die Funktion übergeben, würden Sie eine Nachricht sehr ähnlich zu dieser erhalten: Zu viele Argumente für Finance :: FutureValue bei. f4.pl Zeile 15, in der Nähe von quottime) Ausführung von. f4.pl wegen Kompilierungsfehler abgebrochen. Die Verwendung von Prototypen beim Definieren von Funktionen verhindert, dass Sie Werte senden, die nicht das sind, was die Funktion erwartet. Verwenden Sie oder, um ein Array von Werten zu übergeben. Wenn Sie per Referenz übergeben, verwenden Sie oder, um eine Skalarreferenz für ein Array bzw. einen Hash anzuzeigen. Wenn Sie den Backslash nicht verwenden, werden alle anderen Typen im Argumentlistenprototyp ignoriert. Andere Arten von Disqualifikatoren umfassen ein Und-Zeichen für eine Referenz auf eine Funktion, ein Asterisk für jeden Typ und ein Semikolon, um anzuzeigen, dass alle anderen Parameter optional sind. Betrachten wir nun die Funktionsdeklaration lastMovingAverage, die zwei Ganzzahlen in der Front und ein Array angibt. Die Art und Weise, wie die Argumente in der Funktion verwendet werden, besteht darin, jedem der beiden Skalare, Zähler und Zahl einen Wert zuzuordnen. Während alles andere an das Array gesendet wird. Sehen Sie sich die Funktion getMovingAverage () an, um zu sehen, wie zwei Arrays übergeben werden, um den gleitenden Durchschnitt auf einer Liste von Werten zu erhalten. Die Möglichkeit, die Funktion getMovingAverage aufzurufen, ist in Listing 4.5 dargestellt. Listing 4.5. Mit der gleitenden Mittelwertfunktion. 1 usrbinperl - w 2 3 push (Inc, pwd) 4 Verwendung Finanzen 5 6 Werte (12,22,23,24,21,23,24,23,23,21,29,27,26,28) 7 mv 0) 8 Größe skalar (Werte) 9 print quotn Werte für die Arbeit mit nquot 10 print quot Anzahl der Werte size nquot 11 12 ------------------------ ---------------------------------------- 13 Berechnen Sie den Mittelwert der obigen Funktion 14 - -------------------------------------------------- ------------- 15 ave Finanzen :: getLastAverage (5, Größe, Werte) 16 print quotn Durchschnitt der letzten 5 Tage ave nquot 17 18 Finanzen :: getMovingAve (5, Größe, Werte, mv ) 19 print quotn Moving Average mit 5 Tagen window n nquot Heres die Ausgabe von Listing 4.5: Werte für die Arbeit mit Anzahl der Werte 14 Durchschnitt der letzten 5 Tage 26.2 Die Funktion getMovingAverage () nimmt zwei Skalare und dann zwei Referenzen auf Arrays als Skalare. Innerhalb der Funktion werden die beiden Skalare zu den Arrays zur Verwendung als numerische Arrays dereferenziert. Der zurückgegebene Satz von Werten wird in den Bereich eingefügt, der als der zweite Verweis übergeben wird. Wären die Eingabeparameter nicht für jedes referenzierte Array angegeben worden, wäre der moveAve-Array-Verweis leer gewesen und hätte zur Laufzeit Fehler verursacht. Mit anderen Worten, die folgende Deklaration ist nicht korrekt: sub getMovingAve () Das resultierende spew von Fehlermeldungen von einem schlechten Funktion Prototyp ist wie folgt: Verwendung von nicht initialisierten Wert in Finance. pm Zeile 128. Verwenden von uninitialisierten Wert an Finance. pm Zeile 128. Verwendung des nicht initialisierten Werts in der Zeile "Finance. pm" 128. Verwendung des nicht initialisierten Werts in der Zeile "Finance. pm" 128. Verwendung des nicht initialisierten Werts in der Zeile "Finance. pm" 128. Verwendung des nicht initialisierten Werts in der Zeile "Finance. pm" 133. Verwendung des nicht initialisierten Werts In der Zeile "Finance. pm" 135. Verwendung des nicht initialisierten Werts in der Zeile "Finance. pm" 133. Verwendung des nicht initialisierten Werts in der Zeile "Finance. pm" 135. Verwendung des nicht initialisierten Werts in der Zeile "Finance. pm" 133. Verwendung des nicht initialisierten Werts bei Finance. pm Zeile 135 Verwendung des nicht initialisierten Werts in der Zeile "Finance. pm" 133. Verwendung des nicht initialisierten Werts in der Zeile "Finance. pm" 135. Verwendung des nicht initialisierten Werts in der Zeile "Finance. pm" 133. Verwendung des nicht initialisierten Werts in der Zeile "Finance. pm" 135. Verwendung des nicht initialisierten Werts bei Finance. pm line 133. Use of uninitialized value at Finance. pm line 135. Use of uninitialized value at Finance. pm line 133. Use of uninitialized value at Finance. pm line 135. Use of uninitialized value at Finance. pm line 133. Use of uninitialized value at Finance. pm line 135. Use of uninitialized value at Finance. pm line 133. Use of uninitialized value at Finance. pm line 135. Average of last 5 days 26.2 Moving Average with 5 days window This is obviously not the correct output. Therefore, its critical that you pass by reference when sending more than one array. Global variables for use within the package can also be declared. Look at the following segment of code from the Finance. pm module to see what the default value of the Interest variable would be if nothing was specified in the input. (The current module requires the interest to be passed in, but you can change this.) Heres a little snippet of code that can be added to the end of the program shown in Listing 4.5 to add the ability to set interest rates. 20 local defaultInterest 5.0 21 sub Finance::SetInterest() 22 my rate shift() 23 rate -1 if (rate lt 0) 24 defaultInterest rate 25 printf quotn defaultInterest ratequot 26 The local variable defaultInterest is declared in line 20. The subroutine SetInterest to modify the rate is declared in lines 21 through 26. The rate variable uses the values passed into the subroutine and simply assigns a positive value for it. You can always add more error checking if necessary. To access the defaultInterest variables value, you could define either a subroutine that returns the value or refer to the value directly with a call to the following in your application program: Finance::defaultInterest The variable holding the return value from the module function is declared as my variable . The scope of this variable is within the curly braces of the function only. When the called subroutine returns, the reference to my variable is returned. If the calling program uses this returned reference somewhere, the link counter on the variable is not zero therefore, the storage area containing the returned values is not freed to the memory pool. Thus, the function that declares my pv and then later returns the value of pv returns a reference to the value stored at that location. If the calling routine performs a call like this one: Finance::FVofAnnuity(monthly, rate, time) there is no variable specified here into which Perl stores the returned reference therefore, any returned value (or a list of values) is destroyed. Instead, the call with the returned value assigned to a local variable, such as this one: fv Finance::FVofAnnuity(monthly, rate, time) maintains the variable with the value. Consider the example shown in Listing 4.6, which manipulates values returned by functions. Listing 4.6. Sample usage of the my function. 1 usrbinperl - w 2 3 push(Inc, pwd) 4 use Finance 5 6 monthly 400 7 rate 0.2 i. e. 6 APR 8 time 36 in months 9 10 print quotn ------------------------------------------------quot 11 fv Finance::FVofAnnuity(monthly, rate, time) 12 printf quotn For a monthly 8.2f at a rate of 6.2f for d periodsquot, 13 monthly, rate, time 14 printf quotn you get a future value of 8.2f quot, fv 15 16 fv 1.1 allow 10 gain in the house value. 17 18 mo Finance::AnnuityOfFV(fv, rate, time) 19 20 printf quotn To get 10 percent more at the end, i. e. 8.2fquot, fv 21 printf quotn you need a monthly payment value of 8.2fquot, mo, fv 22 23 print quotn ------------------------------------------------ nquot Here is sample input and output for this function: testme ------------------------------------------------ For a monthly 400.00 at a rate of 0.20 for 36 periods you get a future value of 1415603.75 To get 10 percent more at the end, i. e. 1557164.12 you need a monthly payment value of 440.00 ------------------------------------------------ Modules implement classes in a Perl program that uses the object-oriented features of Perl. Included in object-oriented features is the concept of inheritance . (Youll learn more on the object-oriented features of Perl in Chapter 5. quotObject-Oriented Programming in Perl. quot) Inheritance means the process with which a module inherits the functions from its base classes. A module that is nested within another module inherits its parent modules functions. So inheritance in Perl is accomplished with the :: construct. Heres the basic syntax: SuperClass::NextSubClass. ThisClass. The file for these is stored in. SuperClassNextSubClass133 . Each double colon indicates a lower-level directory in which to look for the module. Each module, in turn, declares itself as a package with statements like the following: package SuperClass::NextSubClass package SuperClass::NextSubClass::EvenLower For example, say that you really want to create a Money class with two subclasses, Stocks and Finance . Heres how to structure the hierarchy, assuming you are in the usrlibperl5 directory: Create a Money directory under the usrlibperl5 directory. Copy the existing Finance. pm file into the Money subdirectory. Create the new Stocks. pm file in the Money subdirectory. Edit the Finance. pm file to use the line package Money::Finance instead of package Finance . Edit scripts to use Money::Finance as the subroutine prefix instead of Finance:: . Create a Money. pm file in the usrlibperl5 directory. The Perl script that gets the moving average for a series of numbers is presented in Listing 4.7. Listing 4.7. Using inheriting modules. 1 usrbinperl - w 2 aa pwd 3 aa . quotMoneyquot 4 push(Inc, aa) 5 use Money::Finance 6 values ( 12,22,23,24,21,23,24,23,23,21,29,27,26,28 ) 7 mv (0) 8 size scalar(values) 9 print quotn Values to work with nquot 10 print quot Number of values size nquot 11 ---------------------------------------------------------------- 12 Calculate the average of the above function 13 ---------------------------------------------------------------- 14 ave Money::Finance::getLastAverage(5,size, values) 15 print quotn Average of last 5 days ave nquot 16 Money::Finance::getMovingAve(5,size, values, mv) 17 foreach i (values) 18 print quotn Moving with 5 days window mvi nquot 19 20 print quotn Moving Average with 5 days window n nquot Lines 2 through 4 add the path to the Money subdirectory. The use statement in line 5 now addresses the Finance. pm file in the. Money subdirectory. The calls to the functions within Finance. pm are now called with the prefix Money::Finance:: instead of Finance:: . Therefore, a new subdirectory is shown via the :: symbol when Perl is searching for modules to load. The Money. pm file is not required. Even so, you should create a template for future use. Actually, the file would be required to put any special requirements for initialization that the entire hierarchy of modules uses. The code for initialization is placed in the BEGIN() function. The sample Money. pm file is shown in Listing 4.8. Listing 4.8. The superclass module for Finance. pm . 1 package Money 2 require Exporter 3 4 BEGIN 5 printf quotn Hello Zipping into existence for younquot 6 7 1 To see the line of output from the printf statement in line 5, you have to insert the following commands at the beginning of your Perl script: use Money use Money::Finance To use the functions in the Stocks. pm module, you use this line: use Money::Stocks The Stocks. pm file appears in the Money subdirectory and is defined in the same format as the Finance. pm file, with the exceptions that use Stocks is used instead of use Finance and the set of functions to export is different. A number of modules are included in the Perl distribution. Check the usrlibperl5lib directory for a complete listing after you install Perl. There are two kinds of modules you should know about and look for in your Perl 5 release, Pragmatic and Standard modules. Pragmatic modules, which are also like pragmas in C compiler directives, tend to affect the compilation of your program. They are similar in operation to the preprocessor elements of a C program. Pragmas are locally scoped so that they can be turned off with the no command. Thus, the command no POSIX turns off the POSIX features in the script. These features can be turned back on with the use statement. Standard modules bundled with the Perl package include several functioning packages of code for you to use. Refer to appendix B, quotPerl Module Archives, quot for a complete list of these standard modules. To find out all the. pm modules installed on your system, issue the following command. (If you get an error, add the usrlibperl5 directory to your path.) find usrlibperl5 - name perl quot. pmquot - print Extension modules are written in C (or a mixture of Perl and C) and are dynamically loaded into Perl if and when you need them. These types of modules for dynamic loading require support in the kernel. Solaris lets you use these modules. For a Linux machine, check the installation pages on how to upgrade to the ELF format binaries for your Linux kernel. The term CPAN (Comprehensive Perl Archive Network) refers to all the hosts containing copies of sets of data, documents, and Perl modules on the Net. To find out about the CPAN site nearest you, search on the keyword CPAN in search engines such as Yahoo. AltaVista, or Magellan. A good place to start is the metronet site . This chapter introduced you to Perl 5 modules and described what they have to offer. A more comprehensive list is found on the Internet via the addresses shown in the Web sites metronet and perl . A Perl package is a set of Perl code that looks like a library file. A Perl module is a package that is defined in a library file of the same name. A module is designed to be reusable. You can do some type checking with Perl function prototypes to see whether parameters are being passed correctly. A module has to export its functions with the EXPORT array and therefore requires the Exporter module. Modules are searched for in the directories listed in the Inc array. Obviously, there is a lot more to writing modules for Perl than what is shown in this chapter. The simple examples in this chapter show you how to get started with Perl modules. In the rest of the book I cover the modules and their features, so hang in there. I cover Perl objects, classes, and related concepts in Chapter 5.With weight vector I mean the vector with weights that you have to multiply the observations in the window that slides over your data with so if you add those products together it returns the value of the EMA on the right side of the window. Für einen linear gewichteten gleitenden Durchschnitt ist die Formel für das Finden des Gewichtsvektors: (1: n) Summe (1: n) (im R-Code). This series of length n adds up to 1. For n10 it will be 0.01818182 0.03636364 0.05454545 0.07272727 0.09090909 0.10909091 0.12727273 0.14545455 0.16363636 0.18181818 the numbers 1 to 10 55, with 55 the sum of the numbers 1 to 10. How do you calculate the weight vector for an exponential moving average (EMA) of length n if n is the length of the window, then alphalt-2(n1) and ilt-1:n so EmaWeightVectorlt-((alpha(1-alpha)(1-i))) Is this correct Even though the EMA is not really confined to a window with a start and an end, shouldnt the weights add up to 1 just like with the LWMA Thanks Jason, any pointers of how to approximate the EMA filter to any desired precision by approximating it with a long-enough FIR filter There39s a perl script on en. wikipedia. orgwikihellip that made the image of the EMA weight vector, but I don39t understand it: if they set the number of weights to 15 why are there 20 red bars instead of 15 ndash MisterH Dec 19 12 at 22:40The belief that a change will be easy to do correctly makes it less likely that the change will be done correctly. An XP programmer writes a unit test to clarify his intentions before he makes a change. We call this test-driven design (TDD) or test-first programming . because an API39s design and implementation are guided by its test cases. The programmer writes the test the way he wants the API to work, and he implements the API to fulfill the expectations set out by the test. Test-driven design helps us invent testable and usable interfaces. In many ways, testability and usability are one in the same. If you can39t write a test for an API, it39ll probably be difficult to use, and vice-versa. Test-driven design gives feedback on usability before time is wasted on the implementation of an awkward API. As a bonus, the test documents how the API works, by example. All of the above are good things, and few would argue with them. One obvious concern is that test-driven design might slow down development. It does take time to write tests, but by writing the tests first, you gain insight into the implementation, which speeds development. Debugging the implementation is faster, too, thanks to immediate and reproducible feedback that only an automated test can provide. Perhaps the greatest time savings from unit testing comes a few months or years after you write the test, when you need to extend the API. The unit test not only provides you with reliable documentation for how the API works, but it also validates the assumptions that went into the design of the API. You can be fairly sure a change didn39t break anything if the change passes all the unit tests written before it. Changes that fiddle with fundamental API assumptions cause the costliest defects to debug. A comprehensive unit test suite is probably the most effective defense against such unwanted changes. This chapter introduces test-driven design through the implementation of an exponential moving average (EMA), a simple but useful mathematical function. This chapter also explains how to use the CPAN modules Test::More and Test::Exception . Unit Tests A unit test validates the programmer39s view of the application. This is quite different from an acceptance test, which is written from the customer39s perspective and tests end-user functionality, usually through the same interface that an ordinary user uses. In constrast, a unit test exercises an API, formally known as a unit. Usually, we test an entire Perl package with a single unit test. Perl has a strong tradition of unit testing, and virtually every CPAN module comes with one or more unit tests. There are also many test frameworks available from CPAN. This and subsequent chapters use Test::More . a popular and well documented test module.2 I also use Test::Exception to test deviance cases that result in calls to die .3 Test First, By Intention Test-driven design takes unit testing to the extreme. Before you write the code, you write a unit test. For example, here39s the first test case for the EMA (exponential moving average) module: This is the minimal Test::More test. You tell Test::More how many tests to expect, and you import the module with useok as the first test case. The BEGIN ensures the module39s prototypes and functions are available during compilation of the rest of the unit test. The next step is to run this test to make sure that it fails: At this stage, you might be thinking, Duh Of course, it fails. Test-driven design does involve lots of duhs in the beginning. The baby steps are important, because they help to put you in the mindset of writing a small test followed by just enough code to satisfy the test. If you have maintenance programming experience, you may already be familiar with this procedure. Maintenance programmers know they need a test to be sure that their change fixes what they think is broken. They write the test and run it before fixing anything to make sure they understand a failure and that their fix works. Test-driven design takes this practice to the extreme by clarifying your understanding of all changes before you make them. Now that we have clarified the need for a module called EMA (duh), we implement it: And, duh, the test passes: Yeeha Time to celebrate with a double cappuccino so we don39t fall asleep. That39s all there is to the test-driven design loop: write a test, see it fail, satisfy the test, and watch it pass. For brevity, the rest of the examples leave out the test execution steps and the concomitant duhs and yeehas. However, it39s important to remember to include these simple steps when test-first programming. If you don39t remember, your programming partner probably will.4 Exponential Moving Average Our hypothetical customer for this example would like to maintain a running average of closing stock prices for her website. An EMA is commonly used for this purpose, because it is an efficient way to compute a running average. You can see why if you look at the basic computation for an EMA: today39s price x weight yesterday39s average x (1 - weight) This algorithm produces a weighted average that favors recent history. The effect of a price on the average decays exponentially over time. It39s a simple function that only needs to maintain two values: yesterday39s average and the weight. Most other types of moving averages, require more data storage and more complex computations. The weight, commonly called alpha . is computed in terms of uniform time periods (days, in this example): 2 (number of days 1) For efficiency, alpha is usually computed once, and stored along with the current value of the average. I chose to use an object to hold these data and a single method to compute the average. Test Things That Might Break Since the first cut design calls for a stateful object, we need to instantiate it to use it. The next case tests object creation: I sometimes forget to return the instance ( self ) so the test calls ok to check that new returns some non-zero value. This case tests what I think might break. An alternative, more extensive test is: This case checks that new returns a blessed reference of class EMA . To me, this test is unnecessarily complex. If new returns something, it39s probably an instance. It39s reasonable to rely on the simpler case on that basis alone. Additionally, there will be other test cases that will use the instance, and those tests will fail if new doesn39t return an instance of class EMA . This point is subtle but important, because the size of a unit test suite matters. The larger and slower the suite, the less useful it will be. A slow unit test suite means programmers will hesitate before running all the tests, and there will be more checkins which break unit andor acceptance tests. Remember, programmers are lazy and impatient, and they don39t like being held back by their programming environment. When you test only what might break, your unit test suite will remain a lightweight and effective development tool. Please note that if you and your partner are new to test-driven design, it39s probably better to err on the side of caution and to test too much. With experience, you39ll learn which tests are redundant and which are especially helpful. There are no magic formulas here. Testing is an art that takes time to master. Satisfy The Test, Don39t Trick It Returning to our example, the implementation of new that satisfies this case is: This is the minimal code which satisfies the above test. length doesn39t need to be stored, and we don39t need to compute alpha. We39ll get to them when we need to. But wait, you say, wouldn39t the following code satisfy the test, too Yes, you can trick any test. However, it39s nice to treat programmers like grown-ups (even though we don39t always act that way). No one is going to watch over your shoulder to make sure you aren39t cheating your own test. The first implementation of new is the right amount of code, and the test is sufficient to help guide that implementation. The design calls for an object to hold state, and an object creation is what needed to be coded. Test Base Cases First What we39ve tested thus far are the base cases . that is, tests that validate the basic assumptions of the API. When we test basic assumptions first, we work our way towards the full complexity of the complete implementation, and it also makes the test more readable. Test-first design works best when the implementation grows along with the test cases. There are two base cases for the compute function. The first base case is that the initial value of the average is just the number itself. There39s also the case of inputting a value equal to the average, which should leave the average unchanged. These cases are coded as follows: The is function from Test::More lets us compare scalar values. Note the change to the instantiation test case that allows us to use the instance ( ema ) for subsequent cases. Reusing results of previous tests shortens the test, and makes it easier to understand. The implementation that satisfies these cases is: The initialization of alpha was added to new . because compute needs the value. new initializes the state of the object, and compute implements the EMA algorithm. self-gt is initially undef so that case can be detected. Even though the implementation looks finished, we aren39t done testing. The above code might be defective. Both compute test cases use the same value, and the test would pass even if, for example, self-gt and value were accidentally switched. We also need to test that the average changes when given different values. The test as it stands is too static, and it doesn39t serve as a good example of how an EMA works. Choose Self-Evident Data In a test-driven environment, programmers use the tests to learn how the API works. You may hear that XPers don39t like documentation. That39s not quite true. What we prefer is self-validating documentation in the form of tests. We take care to write tests that are readable and demonstrate how to use the API. One way to create readable tests is to pick good test data. However, we have a little bootstrapping problem: To pick good test data, we need valid values from the results of an EMA computation, but we need an EMA implementation to give us those values. One solution is to calculate the EMA values by hand. Or, we could use another EMA implementation to come up with the values. While either of these choices would work, a programmer reading the test cases would have to trust them or to recompute them to verify they are correct. Not to mention that we39d have to get the precision exactly right for our target platform. Use The Algorithm, Luke A better alternative is to work backwards through the algorithm to figure out some self-evident test data.5 To accomplish this, we treat the EMA algorithm as two equations by fixing some values. Our goal is to have integer values for the results so we avoid floating point precision issues. In addition, integer values make it easier for the programmer to follow what is going on. When we look at the equations, we see alpha is the most constrained value: today39s average today39s price x alpha yesterday39s average x (1 - alpha) alpha 2 (length 1) Therefore it makes sense to try and figure out a value of alpha that can produce integer results given integer prices. Starting with length 1, the values of alpha decrease as follows: 1, 23, 12, 25, 13, 27, and 14. The values 1, 12, and 25 are good candidates, because they can be represented exactly in binary floating point. 1 is a degenerate case, the average of a single value is always itself. 12 is not ideal, because alpha and 1 - alpha are identical, which creates a symmetry in the first equation: today39s average today39s price x 0.5 yesterday39s average x 0.5 We want asymmetric weights so that defects, such as swapping today39s price and yesterday39s average, will be detected. A length of 4 yields an alpha of 25 (0.4), and makes the equation asymmetric: today39s average today39s price x 0.4 yesterday39s average x 0.6 With alpha fixed at 0.4, we can pick prices that make today39s average an integer. Specifically, multiples of 5 work nicely. I like prices to go up, so I chose 10 for today39s price and 5 for yesterday39s average. (the initial price). This makes today39s average equal to 7, and our test becomes: Again, I revised the base cases to keep the test short. Any value in the base cases will work so we might as well save testing time through reuse. Our test and implementation are essentially complete. All paths through the code are tested, and EMA could be used in production if it is used properly. That is, EMA is complete if all we care about is conformant behavior. The implementation currently ignores what happens when new is given an invalid value for length . Although EMA is a small part of the application, it can have a great impact on quality. For example, if new is passed a length of -1, Perl throws a divide-by-zero exception when alpha is computed. For other invalid values for length . such as -2, new silently accepts the errant value, and compute faithfully produces non-sensical values (negative averages for positive prices). We can39t simply ignore these cases. We need to make a decision about what to do when length is invalid. One approach would be to assume garbage-in garbage-out. If a caller supplies -2 for length . it39s the caller39s problem. Yet this isn39t what Perl39s divide function does, and it isn39t what happens, say, when you try to de-reference a scalar which is not a reference. The Perl interpreter calls die . and I39ve already mentioned in the Coding Style chapter that I prefer failing fast rather than waiting until the program can do some real damage. In our example, the customer39s web site would display an invalid moving average, and one her customers might make an incorrect investment decision based on this information. That would be bad. It is better for the web site to return a server error page than to display misleading and incorrect information. Nobody likes program crashes or server errors. Yet calling die is an efficient way to communicate semantic limits (couplings) within the application. The UI programmer, in our example, may not know that an EMA39s length must be a positive integer. He39ll find out when the application dies. He can then change the design of his code and the EMA class to make this limit visible to the end user. Fail fast is an important feedback mechanism. If we encounter an unexpected die . it tells us the application design needs to be improved. Deviance Testing In order to test for an API that fails fast, we need to be able to catch calls to die and then call ok to validate the call did indeed end in an exception. The function diesok in the module Test::Exception does this for us. Since this is our last group of test cases in this chapter, here39s the entire unit test with the changeds for the new deviance cases highlighted: There are now 9 cases in the unit test. The first deviance case validates that length can39t be negative. We already know -1 will die with a divide-by-zero exception so -2 is a better choice. The zero case checks the boundary condition. The first valid length is 1. Lengths must be integers, and 2.5 or any other floating point number is not allowed. length has no explicit upper limit. Perl automatically converts integers to floating point numbers if they are too large. The test already checks that floating point numbers are not allowed so no explicit upper limit check is required. The implementation that satisfies this test follows: The only change is the addition of a call to die with an unless clause. This simple fail fast clause doesn39t complicate the code or slow down the API, and yet it prevents subtle errors by converting an assumption into an assertion. Only Test The New API One of the most difficult parts of testing is to know when to stop. Once you have been test-infected, you may want to keep on adding cases to be sure that the API is perfect. For example, a interesting test case would be to pass a NaN (Not a Number) to compute . but that39s not a test of EMA . The floating point implementation of Perl behaves in a particular way with respect to NaNs6. and Bivio::Math::EMA will conform to that behavior. Testing that NaNs are handled properly is a job for the Perl interpreter39s test suite. Every API relies on a tremendous amount of existing code. There isn39t enough time to test all the existing APIs and your new API as well. Just as an API should separate concerns so must a test. When testing a new API, your concern should be that API and no others. Solid Foundation In XP, we do the simplest thing that could possibly work so we can deliver business value as quickly as possible. Even as we write the test and implementation, we39re sure the code will change. When we encounter a new customer requirement, we refactor the code, if need be, to facilitate the additional function. This iterative process is called continuous design . which is the subject of the next chapter. It39s like renovating your house whenever your needs change. 7 A system or house needs a solid foundation in order to support continuous renovation. Unit tests are the foundation of an XP project. When designing continuously, we make sure the house doesn39t fall down by running unit tests to validate all the assumptions about an implementation. We also grow the foundation before adding new functions. Our test suite gives us the confidence to embrace change. Quality Software Management: Vol. 1 Systems Thinking . Gerald Weinberg, Dorset House, 1991, p. 236. Part of the Test-Simple distribution, available at search. cpan. orgsearchqueryTest-Simple I used version 0.47 for this book. Just a friendly reminder to program in pairs, especially when trying something new. Thanks to Ion Yadigaroglu for teaching me this technique. In some implementations, use of NaNs will cause a run-time error. In others, they will cause all subsequent results to be a NaN. Don39t let the thought of continuous house renovation scare you off. Programmers are much quieter and less messy than construction workers.


No comments:

Post a Comment