Questo capitolo presenta i concetti dietro riferimenti ai moduli Perl, pacchetti e classi. Esso mostra anche come creare un paio di moduli di esempio. Un modulo Perl è un insieme di codice Perl che si comporta come una libreria di chiamate di funzione. Il modulo termine in Perl è sinonimo con il pacchetto di parola. I pacchetti sono una caratteristica di Perl 4, mentre i moduli sono prevalenti in Perl 5. È possibile mantenere tutto il codice Perl riutilizzabile specifico di una serie di compiti in un modulo Perl. Pertanto, tutte le funzionalità appartenenti ad un tipo di attività è contenuto in un file. La sua più facile costruire un'applicazione su questi blocchi modulari. Quindi, il modulo word applica un po 'più di pacchetto. Ecco una breve introduzione di moduli. Alcuni argomenti di questa sezione saranno trattati in dettaglio in tutto il resto del libro. Leggere con attenzione le seguenti paragrafi per avere una panoramica di ciò che ci aspetta, come si scrive e utilizzare i propri moduli. Ciò che è fonte di confusione è che il modulo di termini e il pacchetto vengono usati in modo intercambiabile in tutta la documentazione di Perl, e questi due termini significa la stessa cosa. Così, quando la lettura di documenti Perl, basti pensare quotpackagequot quando si vede quotmodulequot e viceversa. Così, che cosa è la premessa per l'utilizzo di moduli Ebbene, i moduli sono lì per confezione (scusate il gioco di parole) variabili, simboli e elementi di dati interconnessi tra loro. Ad esempio, utilizzando le variabili globali con nomi molto comuni come k. j. o io in un programma non è generalmente una buona idea. Inoltre, un contatore del ciclo, i. dovrebbe essere consentito di lavorare in modo indipendente in due diverse porzioni di codice. Dichiarare i come una variabile globale e quindi incrementando dall'interno di una subroutine creerà problemi ingestibili con il codice dell'applicazione, perché la subroutine potrebbe essere stato chiamato da all'interno di un ciclo che utilizza anche una variabile denominata i. L'uso di moduli in Perl permette variabili con lo stesso nome per essere creati in diversi, luoghi diversi nello stesso programma. I simboli definiti per le variabili sono memorizzati in un array associativo, indicato come una tabella di simboli. Queste tabelle di simboli sono unici per un pacchetto. Pertanto, variabili dello stesso nome in due pacchetti diversi possono avere valori diversi. Ogni modulo ha la sua tabella dei simboli di tutti i simboli che sono dichiarati all'interno di esso. La tabella dei simboli isola fondamentalmente nomi sinonimi in un modulo di un altro. La tabella dei simboli definisce uno spazio dei nomi. cioè, uno spazio per nomi di variabili indipendenti esistono in. Pertanto, l'utilizzo di moduli, ciascuno con la propria tabella di simboli, impedisce una variabile dichiarata in una sezione di sovrascrivere i valori di altre variabili con lo stesso nome dichiarato altrove nella stessa programma. È un dato di fatto, tutte le variabili in Perl appartengono a un pacchetto. Le variabili in un programma Perl appartengono al pacchetto principale. Tutti gli altri pacchetti all'interno di un programma Perl o sono annidati all'interno di questo pacchetto principale o esistono allo stesso livello. Ci sono alcune variabili veramente globale, come ad esempio la matrice gestore di segnale SIG. che sono disponibili per tutti gli altri moduli di programma applicativo e non può essere isolato tramite namespace. Solo gli identificatori di variabili che iniziano con le lettere o un carattere di sottolineatura sono conservati in una tabella dei simboli moduli. Tutti gli altri simboli, come i nomi stdin. STDOUT. STDERR. ARGV. ARGVOUT. ENV. Inc. e SIG sono costretti a essere in pacchetto principale. La commutazione tra i pacchetti colpisce solo namespace. Tutto quello che stanno facendo quando si utilizza un unico pacchetto o l'altro sta dichiarando che tabella dei simboli da utilizzare come tabella dei simboli di default per la ricerca dei nomi delle variabili. Solo le variabili dinamiche sono influenzati dall'uso di tabelle di simboli. Le variabili dichiarate con l'uso della mia parola chiave sono ancora risolti con il blocco di codice capita di risiedere in e non si fa riferimento attraverso tabelle dei simboli. Infatti, la portata di una dichiarazione pacchetto rimane attiva solo all'interno del blocco di codice che viene dichiarato in. Pertanto, se si passa tabelle dei simboli utilizzando un pacchetto all'interno di una subroutine, la tabella dei simboli originale in vigore quando è stata effettuata la chiamata verrà ripristinato quando la subroutine restituisce. Il passaggio tabelle dei simboli riguarda solo la ricerca di default dei nomi delle variabili dinamiche. È ancora possibile fare esplicito riferimento a variabili, file handle, e così via in un pacchetto specifico anteponendo un packageName. per il nome della variabile. Hai visto quello che un contesto pacchetto è stato quando si utilizzano i riferimenti nel capitolo 3. Un contesto pacchetto implica semplicemente l'uso della tabella dei simboli dall'interprete Perl per la risoluzione dei nomi delle variabili in un programma. Con il passaggio tabelle dei simboli, si sta passando il contesto pacchetto. I moduli possono essere nidificati all'interno di altri moduli. Il modulo nidificato può utilizzare le variabili e le funzioni del modulo si è annidato all'interno. Per i moduli nidificati, si dovrebbe usare moduleName. nestedModuleName e così via. Utilizzando il doppio due punti (::) è sinonimo con l'utilizzo di un preventivo back (). Tuttavia, il doppio colon è il preferito modo, il futuro di affrontare variabili all'interno di moduli. Esplicita l'indirizzamento delle variabili modulo è sempre fatto con un riferimento completo. Ad esempio, supponiamo di avere un modulo, per gli investimenti. che è il pacchetto predefinito in uso, e si vuole affrontare un altro modulo, obbligazioni. che è nidificato all'interno del modulo per gli investimenti. In questo caso, non è possibile utilizzare legame ::. Invece, si dovrebbe utilizzare per gli investimenti :: :: legame di affrontare variabili e funzioni all'interno del modulo Bond. Utilizzando Legame :: implicherebbe l'utilizzo di un legame pacchetto che è annidato all'interno del modulo principale e non all'interno del modulo investimenti. La tabella dei simboli per un modulo è effettivamente memorizzato in un array associativo dei moduli allegati nomi con due punti. La tabella dei simboli per un modulo chiamato Legame verrà indicato come array associativo legame ::. Il nome per la tabella dei simboli per il modulo principale è principale ::. e può anche essere abbreviato in ::. Allo stesso modo, tutti i pacchetti nidificati hanno i loro simboli memorizzati in array associativi con doppio due punti che separano ogni livello di nidificazione. Ad esempio, nel modulo legame che è nidificato all'interno del modulo per gli investimenti, l'array associativo per i simboli nel modulo di Bond si chiamerà investimenti :: :: James Bond. Un typeglob è davvero un tipo globale per un nome del simbolo. È possibile eseguire operazioni di aliasing assegnando ad un typeglob. Uno o più voci in un array associativo per i simboli saranno usati quando si usa un'assegnazione tramite un typeglob. Il valore reale in ogni voce del array associativo è quello che si fa riferimento a quando si utilizza la notazione nomeVariabile. Quindi, ci sono due modi di riferimento per i nomi delle variabili in un pacchetto: investimento :: :: soldi di investimento bollette Nel primo metodo, si fa riferimento alle variabili tramite un riferimento typeglob. L'uso della tabella dei simboli, Investment ::. è implicito qui, e Perl ottimizzerà la ricerca per i simboli di denaro e le bollette. Questo è il modo di affrontare un simbolo più veloce e comodo. Il secondo metodo utilizza una ricerca per il valore di una variabile indirizzata da denaro e fatture nella matrice associativa usata per i simboli, Investment :: esplicitamente. Questa ricerca sarebbe fatto dinamicamente e non sarà ottimizzata Perl. Pertanto, la ricerca sarà costretto a verificare l'array associativo ogni volta che viene eseguita l'istruzione. Come risultato, il secondo metodo non è efficiente e deve essere utilizzato solo per la dimostrazione di come la tabella dei simboli è implementata internamente. Un altro esempio in questa informativa Kamran Husain provoca variabili, subroutine maniglie, e di file che sono denominati con il Kamran simbolo anche essere affrontati attraverso la Husain simbolo. Cioè, tutte le voci di simboli nella tabella dei simboli corrente con il Kamran chiave ora conterrà riferimenti a quei simboli affrontati dal Husain chiave. Per evitare che un incarico così globale, è possibile utilizzare riferimenti espliciti. Ad esempio, la seguente dichiarazione vi permetterà di affrontare il contenuto del Husain tramite il Kamran variabile. Kamran Husain Tuttavia, gli array come Kamran e Husain non sarà lo stesso. Solo ciò che i riferimenti indicati esplicitamente verranno modificati. Per riassumere, quando si assegna un typeglob ad un altro, si hanno effetto su tutte le voci in una tabella di simboli, indipendentemente dal tipo di variabile da cui. Quando si assegna un riferimento da un tipo di variabile ad un altro, si sta solo interessando una voce nella tabella dei simboli. Un file di modulo Perl ha il seguente formato: pacchetto ModuleName. Inserisci il codice del modulo. 1 Il nome del file deve essere chiamato ModuleName. pm. Il nome di un modulo deve terminare nel. pm stringa per convenzione. L'istruzione package è la prima riga del file. L'ultima riga del file deve contenere la linea con il 1 dichiarazione. Questo in effetti restituisce un valore vero al programma applicativo utilizzando il modulo. Non usando il 1 dichiarazione non farà si che il modulo di essere caricato correttamente. L'istruzione package indica all'interprete Perl di iniziare con un nuovo dominio dello spazio dei nomi. In sostanza, tutte le variabili in uno script Perl appartengono ad un pacchetto chiamato principale. Ogni variabile nel pacchetto principale può essere definito come mainvariable. Ecco la sintassi per tali riferimenti: packageNamevariableName L'apostrofo () è sinonimo di doppio due punti (::) dell'operatore. Copro più usi dell'operatore :: nel prossimo capitolo. Per il momento, è necessario ricordare che le due istruzioni seguenti sono equivalenti: packageNamevariableName packageName :: nomeVariabile La sintassi doppio colon è considerato standard nel mondo Perl. Pertanto, per preservare la leggibilità, io uso la sintassi doppio colon nel resto di questo libro a meno che la sua assolutamente necessario fare eccezioni per dimostrare una tesi. L'uso di default di un nome di variabile rimanda al pacchetto corrente attiva al momento della compilazione. Così, se nel pacchetto Finance. pm e specificare un pv variabile. la variabile è in realtà pari a Finance :: pv. Utilizzando moduli Perl: utilizzare vs. richiedere includere moduli Perl nel vostro programma utilizzando l'uso o la dichiarazione richiedono. Ecco il modo per utilizzare una di queste affermazioni: utilizzare ModuleName richiede ModuleName Nota che l'estensione. pm non viene utilizzato nel codice sopra indicato. Si noti inoltre che né istruzione consente un file da includere più di una volta in un programma. Il valore restituito di vero (1) come l'ultima istruzione è necessaria per far Perl sapere che un richiedono d o l'uso d modulo caricato correttamente e permette l'interprete Perl ignora eventuali ricariche. In generale, è meglio utilizzare l'istruzione all'uso del modulo di dichiarazione richiedere modulo in un programma Perl per essere compatibile con le versioni future di Perl. Per i moduli, si potrebbe prendere in considerazione di continuare ad utilizzare l'istruzione necessaria. Ecco perché: l'istruzione USE fa un po 'più di lavoro rispetto alla dichiarazione richiedere in quanto altera il namespace del modulo che include un altro modulo. Si desidera che questo aggiornamento in più dello spazio dei nomi da fare in un programma. Tuttavia, quando si scrive codice per un modulo, non si può decidere lo spazio dei nomi per essere modificato a meno che la sua esplicita richiesta. In tal caso, si utilizzerà la richiedono dichiarazione. La dichiarazione richiedono include il percorso completo di un file nella matrice Inc in modo che le funzioni e le variabili nel file moduli sono in una posizione conosciuta durante il tempo di esecuzione. Pertanto, le funzioni che vengono importati da un modulo vengono importati tramite un modulo di riferimento esplicito in fase di esecuzione con l'affermazione richiede. La dichiarazione uso fa la stessa cosa come richiedono economico poiché aggiorna la matrice Inc con tutti i percorsi di moduli caricati. Il codice per la funzione d'uso va anche un ulteriore passo avanti e chiama una funzione di importazione del modulo è l'uso d caricare esplicitamente l'elenco delle funzioni esportate in fase di compilazione, risparmiando così il tempo necessario per una risoluzione esplicita di un nome di funzione durante l'esecuzione. In sostanza, la dichiarazione uso è equivalente a richiedere ModuleName lista importazione ModuleName delle funzioni importate L'uso della dichiarazione uso non modificare il programma dello spazio dei nomi, perché i nomi delle funzioni importati vengono inseriti nella tabella dei simboli. L'affermazione richiede non altera il vostro programmi namespace. Pertanto, la seguente dichiarazione utilizzare ModuleName () è equivalente a questa dichiarazione: richiede funzioni ModuleName sono importati da un modulo tramite una chiamata a una funzione chiamata di importazione. È possibile scrivere la propria funzione di importazione in un modulo, oppure è possibile utilizzare il modulo Exporter e utilizzare la sua funzione di importazione. In quasi tutti i casi, si utilizzerà il modulo Exporter per fornire una funzione di importazione invece di reinventare la ruota. (Youll saperne di più su questo nella prossima sezione.) Se non si decide di utilizzare il modulo Exporter, si dovrà scrivere la propria funzione di importazione in ogni modulo che si scrive. La sua molto più facile usare semplicemente il modulo Exporter e lasciare che Perl fare il lavoro per voi. Il campione Letter. pm modulo Il modo migliore per illustrare la semantica del modo in cui un modulo viene utilizzato in Perl è quello di scrivere un modulo semplice e mostrare come usarlo. Diamo l'esempio di uno strozzino locale, Rudious Massimo, che è semplicemente stanco di scrivere la stessa quotrequest per le lettere paymentquot. Essendo un fan accanito di computer e Perl, Rudious adotta l'approccio programmatori pigri e scrive un modulo Perl per aiutarlo a generare i suoi appunti e le lettere. Ora, invece di digitare all'interno di campi in un file di modello appunto, tutto quello che deve fare è digitare poche righe per produrre il suo bello, nota minacciosa. 4.1 vi mostra quello che ha da digitare. 4.1. Utilizzando il modulo Lettera. 1 usrbinperl - w 2 3 Rimuovere il commento la riga sotto per includere la directory corrente in Inc. 4 push (Inc, pwd) 5 6 7 8 uso Lettera Lettera :: A (quotMr. Gioco d'azzardo Manquot, soldi quotThe per Lucky Dog, Gara 2quot) 9 Lettera :: ClaimMoneyNice () 10 Lettera :: ThankDem () 11 Lettera :: Fine () la dichiarazione uso Letter è presente per forzare l'interprete Perl per includere il codice per il modulo nel programma applicativo. Il modulo deve essere posizionato nella directory usrlibperl5, oppure è possibile inserirlo in qualsiasi directory elencata nella matrice Inc. L'array Inc è la lista di directory che l'interprete Perl cercare quando si cerca di caricare il codice per il modulo di nome. La linea commentata (numero 4) mostra come aggiungere la directory di lavoro corrente per includere il percorso. Le successive quattro righe nel file generano l'oggetto della lettera. Heres l'uscita dal utilizzando il modulo Lettera: A: Mr. Gambling Man Fm: Rudious Massimo, Loan Shark Dt: lun 7 feb 10:35:51 CST 1996 Re: I soldi per Lucky Dog, Gara 2 Si è venuto alla mia attenzione che il tuo account è il modo sopra dovuto. Hai intenzione di noi paga prima o vuoi che ti piacerebbe venire ovah Grazie per il vostro sostegno. Il file di modulo di lettera è mostrato nel Listato 4.2. Il nome del pacchetto è dichiarato nella prima riga. Perché questo moduli saranno esportati funzioni, io uso il modulo Exporter. Pertanto, l'uso Esportatore dichiarazione è necessaria per ereditare la funzionalità dal modulo Exporter. Un altro passo necessario è mettere la parola esportato nella matrice ISA per consentire la ricerca di Exported. pm. La matrice di ISA è una matrice speciale all'interno di ogni pacchetto. Ogni elemento nelle liste di array dove altro cercare un metodo, se non può essere trovata nel pacchetto corrente. L'ordine in cui i pacchetti sono elencati nella matrice ISA è l'ordine in cui Perl cerca simboli non risolti. Una classe che è elencato nella matrice ISA si riferisce a come la classe base di quella particolare classe. Perl nella cache i metodi mancanti si trovano in classi di base per futuri riferimenti. Modifica la matrice ISA svuotare la cache e causare Perl per cercare tutti i metodi di nuovo. Ora lascia guardare il codice per Letter. pm nel Listato 4.2. 4.2. Il modulo Letter. pm. 1 confezione Lettera 2 3 4 richiedono Esportatore ISA (Esportatore) 5 6 head1 NOME 7 8 Lettera - modulo di esempio per generare carta intestata per voi 9 10 head1 SINOSSI 11 12 utilizzo Lettera 13 14 Lettera :: Date () 15 Lettera :: A (nome , azienda, indirizzo) 16 17 Allora uno dei seguenti: 18 Lettera :: ClaimMoneyNice () 19 Lettera :: ClaimMoney () 20 Lettera :: ThreatBreakLeg () 21 22 Lettera :: ThankDem () 23 Lettera :: Fine () 24 25 head1 DESCRIZIONE 26 27 Questo modulo fornisce un breve esempio di generare una lettera per un usuraio 28 amichevole neighborbood. 29 30 Il codice inizia dopo l'istruzione quotcutquot. 31 tagliati 32 33 EXPORT QW (data, 34 A, 35 ClaimMoney, 36 ClaimMoneyNice, 37 ThankDem, 38 Fine) 39 40 41 Stampa data odierna 42 43 sub lettera :: Data 44 Data Data 45 Stampa quotn Oggi è datequot 46 47 48 sub lettera :: Per 49 locale (nome) spostamento di 50 locali (soggetto) spostamento 51 quotn stampa Per: namequot 52 stampa quotn Fm: Rudious Massimo, prestito Sharkquot 53 stampa quotn Dt: quot, data 54 stampa quotn Re: subjectquot 55 stampa quotnnquot 56 stampare quotnnquot 57 58 sub lettera :: ClaimMoney () 59 stampa quotn Tu mi devi dei soldi. Ottenere il vostro atto togetherquot 60 quotn stampa Vuoi che mandi Bruno verso quot 61 di stampa quotn raccoglierlo. o sei pagherai upquot 62 63 64 sub lettera :: ClaimMoneyNice () 65 stampa quotn E 'venuto alla mia attenzione che il tuo account è quot 66 quotn stampa strada sopra due. quot 67 di stampa quotn Hai intenzione di noi paga soon..quot 68 quotn stampa o volete me di venire ovahquot 69 70 71 sub lettera :: ThreatBreakLeg () 72 stampa quotn apparentemente lettere come questi dont helpquot 73 quotn stampa dovrò fare un esempio di youquot quotn 74 di stampa n Ci vediamo in ospedale , palquot 75 76 77 sub lettera :: ThankDem () 78 stampa quotnn Grazie per la tua supportquot 79 80 81 sub lettera :: Fine () 82 printf quotnnnn Sincerelyquot 83 printf quotn Rudious n quot vengono utilizzati 84 85 86 1 Linee che contengono il segno di uguale per la documentazione. È necessario documentare ogni modulo per i moduli Perl proprio di riferimento non hanno bisogno di essere documentato, ma è una buona idea di scrivere poche righe su quello che il codice fa. A pochi anni da adesso, si può dimenticare ciò che un modulo è di circa. Una buona documentazione è sempre un must se si vuole ricordare quello che hai fatto in passato copro stili di documentazione utilizzati per Perl nel capitolo 8. quotDocumenting Perl Scripts. quot Per questo modulo di esempio, la dichiarazione head1 inizia la documentazione. Tutto fino alla dichiarazione di taglio viene ignorato dal interprete Perl. Successivamente, il modulo sono elencate tutte le funzioni esportate da questo modulo nella matrice EXPORT. L'array EXPORT definisce tutti i nomi delle funzioni che possono essere chiamati dal codice esterno. Se non si elencano una funzione in questo array EXPORT, è solito essere visto dai moduli di codice esterni. Seguendo la matrice EXPORT è il corpo del codice, una subroutine alla volta. Dopo che tutti i sottoprogrammi sono definiti, la dichiarazione finale 1 chiude il file del modulo. 1 deve essere l'ultima riga eseguibile nel file. Vediamo alcune delle funzioni definite in questo modulo. La prima funzione da guardare è la semplice funzione di data, le linee da 43 a 46, che stampa la data di UNIX e l'ora correnti. Non ci sono parametri di questa funzione, e doesnt ritorno qualcosa di significativo al chiamante. Si noti l'uso del mio prima della variabile data in linea 44. La mia parola chiave viene utilizzata per limitare l'ambito della variabile all'interno delle funzioni di Data parentesi graffe. Codice tra parentesi graffe viene definito come un blocco. Le variabili dichiarate all'interno di un blocco sono di portata limitata entro le parentesi graffe. In 49 e 50, il nome e soggetto variabili locali sono visibili a tutte le funzioni. È inoltre possibile dichiarare le variabili con il qualificatore locale. L'uso di locale consente una variabile di essere portata per il blocco corrente e per altri blocchi di codice chiamati dall'interno di questo blocco. Così, un x locali dichiarate all'interno di un blocco è visibile a tutti i blocchi successivi chiamate dall'interno di questo blocco e può fare riferimento. Nel seguente codice di esempio, la variabile nome funzioni ToTitled si può accedere, ma non i dati in iPhone. 1 sub lettera :: ToTitled 2 locale (nome) spostamento 3 il mio (telefono) spostare il codice di esempio per Letter. pm ha mostrato come estrarre un parametro alla volta. La subroutine a () accetta due parametri per impostare l'intestazione per il promemoria. Uso delle funzioni all'interno di un modulo non è diversa rispetto all'utilizzo e la definizione di moduli Perl all'interno dello stesso file di codice. I parametri sono passati per riferimento, se non diversamente specificato. array multipli passati in una subroutine, se non esplicitamente dereferenziati utilizzando la barra rovesciata, sono concatenati. L'array di input in una funzione è sempre una matrice di valori scalari. Passando valori di riferimento è il modo preferito in Perl per passare una grande quantità di dati in una subroutine. (Vedere il Capitolo 3. quotReferences. quot) Un altro modulo di esempio: Finanza Il modulo di Finanza, mostrato nel Listato 4.3, viene utilizzato per fornire semplici calcoli per i valori di prestito. Utilizzando il modulo Finance è semplice. Tutte le funzioni sono scritte con gli stessi parametri, come mostrato nella formula per le funzioni. Vediamo come il valore futuro di un investimento può essere calcolato. Ad esempio, se si investe qualche dollaro, pv. in un legame che offre un tasso percentuale fissa, r. applicato ad intervalli noti per periodi di tempo n, qual è il valore del titolo al momento della sua scadenza In questo caso, youll essere utilizzando la seguente formula: fv pv (1r) n La funzione per ottenere il valore futuro è dichiarata come FutureValue . Fare riferimento a 4.3 per vedere come usarlo. 4.3. Utilizzando il modulo Finanze. 1 usrbinperl - w 2 3 push (Inc, pwd) 4 uso Finance 5 6 prestito 5000.00 7 apr 3.5 8 aprile dell'esercizio 10 anni. 9 10 ------------------------------------------------ ---------------- 11 Calcolare il valore alla fine del mutuo se l'interesse 12 viene applicato ogni anno. 13 ------------------------------------------------- --------------- 14 tempo dell'anno 15 FV1 Finanza :: FutureValue (prestito, apr, tempo) quotn 16 di stampa Se l'interesse viene applicato alla fine del yearquot 17 stampa quotn Il valore futuro di un prestito di quot. prestito. quotnquot 18 quot stampa a un TAEG del quot, aprile quot per quot, tempo, quot yearsquot 19 printf quot è 8.2f nquot. FV1 20 21 ----------------------------------------------- ----------------- 22 Calcolare il valore alla fine del prestito se l'interesse viene applicato il 23 di ogni mese. 24 ------------------------------------------------- --------------- 25 rate 12 apr 26 apr tempo dell'anno 12 a 27 mesi FV2 Finanza :: FutureValue (prestito, tasso, tempo) quotn 28 29 Stampa Se l'interesse viene applicato alla fine del ogni monthquot 30 di stampa quotn Il valore futuro di un prestito di quot. prestito. quotnquot 31 quot stampa a un TAEG del quot, aprile quot per quot, tempo, quot monthsquot 32 printf quot è 8.2f nquot. FV2 33 34 printf quotn La differenza di valore è 8.2fquot, FV2 - FV1 35 printf quotn Pertanto applicando interesse al tempo più breve periodsquot 36 printf quotn ci sono in realtà sempre più soldi in interest. nquot Ecco input e output del Listato 4.3 campione. TestMe Se l'interesse viene applicato a fine anno il valore futuro di un prestito di 5000 a un TAEG del 3,5 per 10 anni è 7052,99 Se l'interesse viene applicato alla fine di ogni mese il valore futuro di un prestito di 5000 a un TAEG del 3,5 per 120 mesi è 7.091,72 La differenza di valore è 38.73 Pertanto, applicando interessi in periodi di tempo più brevi ci sono in realtà sempre più soldi in interessi. La rivelazione in uscita è il risultato del confronto di valori tra FV1 e FV2. Il valore FV1 viene calcolato con l'applicazione di interesse una volta all'anno durante la vita del legame. FV2 è il valore se l'interesse viene applicato ogni mese al tasso di interesse mensile equivalente. Il pacchetto Finance. pm è mostrato nel Listato 4.4 nelle sue prime fasi di sviluppo. 4.4. Il pacchetto Finance. pm. 1 pacchetto di Finanza 2 3 richiede Esportatore 4 ISA (Esportatore) 5 6 7 8 head1 Finance. pm calcolatrice finanziaria - calcoli finanziari facili con il Perl 9 10 2 11 testa utilizzo delle Finanze 12 13 pv 10000.0 14 15 tasso di 12,5 12 APR al mese. 16 17 il tempo di 360 mesi per il prestito a maturare 18 19 fv FutureValue () 20 21 stampa fv 22 23 tagliati 24 25 EXPORT QW (FutureValue, 26 Valore Attuale, 27 FVofAnnuity, 28 AnnuityOfFV, 29 getLastAverage, 30 getMovingAverage, 31 SetInterest) 32 33 34 globals, se del caso defaultInterest 35 36 37 38 39 locale 5.0 sub Finanza :: SetInterest () 40 mio turno tasso () 41 rate defaultInterest 42 printf quotn defaultInterest ratequot 43 44 45 -------------- -------------------------------------------------- ---- 46 Note: 47 1. Il tasso di interesse r è dato in un valore di 0-100. 48 2. Il n proposta nei termini è il tasso al quale viene applicato l'interesse 49. 50 51 ------------------------------------------------ -------------------- 52 53 ---------------------------- ---------------------------------------- 54 valore attuale di un investimento dato 55 fv - un futuro valore di 56 r - tasso per periodo 57 n - numero di periodo di 58 ---------------------------------- ---------------------------------- 59 sub Finanza :: FutureValue () 60 mio (pv, R, n ) 61 la mia fv PV ((1 (R100)) n) 62 ritorno fv 63 64 65 ------------------------------ -------------------------------------- 66 valore attuale di un investimento dato 67 fv - un futuro valore di 68 r - tasso per periodo 69 n - numero di periodo di 70 ------------------------------------ -------------------------------- 71 sub Finanza :: Valore Attuale () 72 mio pv 73 mio (fv, R, n) 74 pv fv ((1 (R100)) n) 75 ritorno pv 76 77 78 79 ----------------------------- --------------------------------------- 80 Prendi il valore futuro di una rendita data 81 mp - Il pagamento mensile di rendita 82 r - tasso per periodo 83 n - numero di periodo di 84 -------------------------------- ------------------------------------ 85 86 sub FVofAnnuity () 87 mio fv 88 mio Oner 89 mio (mp, r, n) 90 91 ONER (1 r) n 92 fv MP ((Oner - 1) r) 93 ritorno fv 94 95 96 ------------------ -------------------------------------------------- 97 Prendi il vitalizio dai seguenti bit di informazione 98 r - tasso per periodo 99 n - numero di periodo di 100 fv - Valore futuro 101 ---------------------- ---------------------------------------------- 102 103 sub AnnuityOfFV () 104 mio mp mp - il pagamento mensile di rendita 105 mia Oner 106 mio (fv, r, n) 107 108 ONER (1 r) n 109 mp fv (r (Oner - 1)) 110 ritorno mp 111 112 113 - -------------------------------------------------- ---------------- 114 ottenere la media degli ultimi valori quotnquot in un array. 115 ------------------------------------------------- ------------------- 116 l'ultimo numero conteggio di elementi dell'array in valori 117 il numero totale di elementi in valori è in numero di 118 119 sub getLastAverage () 120 mia (conteggio, il numero, i valori) 121 mio i 122 123 mio a 0 124 0 ritorno, se (conta 0) 125 per (i 0 numero ilt i) 126 un valuesnumber - i - 1 127 128 di ritorno un numero 129 130 131 --- -------------------------------------------------- --------------- 132 Ottenere una media mobile dei valori. 133 ------------------------------------------------- ------------------- 134 la dimensione della finestra è il primo parametro, il numero di elementi nella matrice passata 135 è vicino. (Questo può essere facilmente calcolato all'interno della funzione 136 utilizzando la funzione scalare (), ma la subroutine illustrata 137 viene usato anche per illustrare come passare puntatori.) Il riferimento al 138 matrice di valori è passati successiva, seguita da una riferimento al luogo 139 i valori di ritorno sono da memorizzare. 140 141 sub getMovingAve () 142 mio (conteggio, numero, valori, movingAve) 143 mia i 144 mio di 0 145 mio v 0 146 147 ritorno 0 if (conta 0) 148 ritorno -1 se (contare il numero GT) 149 ritorno - 2 se (contare lt 2) 150 151 movingAve0 0 152 movingAvenumber - 1 0 153 per (I0 iltcounti) 154 v valuesi contano 155 av 156 movingAvei 0 157 158 per (iltnumberi iCount) 159 v valuesi contano 160 av 161 v valuesi - contare - 1 162 a - v conta 163 movingAvei un ritorno 0 166 167 168 1 164 165 Guardate alla dichiarazione della funzione FutureValue con (). I tre segni del dollaro insieme significano tre numeri scalari di essere passato alla funzione. Questo scoping in più è presente per convalidare il tipo di parametri passati alla funzione. Se si dovesse passare una stringa invece di un numero nella funzione, si otterrebbe un messaggio molto simile a questo: troppi argomenti per Finance :: FutureValue alla linea. f4.pl 15, nei pressi di quottime) quot Esecuzione di. f4.pl interrotta a causa di errori di compilazione. L'uso di prototipi al momento di definire le funzioni impedisce l'invio di valori diversi da quello che la funzione si aspetta. Utilizzare o per passare una matrice di valori. Se siete di passaggio per riferimento, utilizzare o per mostrare un riferimento ad uno scalare di un array o hash, rispettivamente. Se non si utilizza la barra rovesciata, tutti gli altri tipi di prototipo lista degli argomenti vengono ignorati. Altri tipi di disqualifiers includono una commerciale per un riferimento a una funzione, un asterisco per ogni tipo e una virgola per indicare che tutti gli altri parametri sono opzionali. Ora, consente di guardare la dichiarazione di funzione lastMovingAverage, che specifica due interi nella parte anteriore seguito da un array. Il modo in cui gli argomenti sono utilizzati nella funzione è quella di assegnare un valore a ciascuna delle due scalari, contare e numero. mentre tutto il resto viene inviato alla matrice. Guardate la funzione di getMovingAverage () per vedere come due array vengono passati al fine di ottenere la media mobile su un elenco di valori. Il modo per chiamare la funzione getMovingAverage è mostrato nel Listato 4.5. Listato 4.5. Utilizzando la funzione di media mobile. 1 usrbinperl - w 2 3 push (Inc, pwd) 4 uso Finance 5 6 valori (12,22,23,24,21,23,24,23,23,21,29,27,26,28) 7 mv ( 0) 8 dimensione scalare (valori) valori 9 stampa quotn di lavorare con nquot 10 di stampa quot Numero di dimensioni valori nquot 11 12 ------------------------ ---------------------------------------- 13 Calcolare la media della funzione sopra 14 - -------------------------------------------------- ------------- 15 ave Finanza :: getLastAverage (5, dimensioni, valori) 16 Stampa quotn media degli ultimi 5 giorni nquot ave 17 18 Finance :: getMovingAve (5, le dimensioni, i valori, mv ) 19 stampa quotn media mobile con finestra 5 giorni n nquot Heres l'uscita dal 4.5: valori di lavorare con il numero di valori 14 media degli ultimi 5 giorni 26.2 la funzione getMovingAverage () prende due scalari e poi due riferimenti di array come scalari. All'interno della funzione, i due scalari verso le matrici sono dereferenziati per uso come matrici numeriche. L'insieme dei valori restituiti è inserito nella zona passata come secondo riferimento. Avevano i parametri di input non sono stati specificati con per ogni array di riferimento, il riferimento di matrice movingAve sarebbe stato vuoto e avrebbe causato errori in fase di esecuzione. In altre parole, la seguente dichiarazione non è corretta: sub getMovingAve () La vomitare risultante di messaggi di errore da un prototipo di funzione cattiva è la seguente: l'uso di valore non inizializzato in linea Finance. pm 128. L'utilizzo di valore non inizializzato in linea Finance. pm 128. L'utilizzo di valore non inizializzato in linea Finance. pm 128. L'utilizzo di valore non inizializzato in linea Finance. pm 128. L'utilizzo di valore non inizializzato in linea Finance. pm 128. L'utilizzo di valore non inizializzato in linea Finance. pm 133. L'utilizzo di valore non inizializzato in linea di Finance. pm 135. L'utilizzo di valore non inizializzato in linea Finance. pm 133. L'utilizzo di valore non inizializzato in linea Finance. pm 135. L'utilizzo di valore non inizializzato in linea Finance. pm 133. L'utilizzo di valore non inizializzato a Finance. pm linea 135 . usare di valore non inizializzato in linea Finance. pm 133. L'utilizzo di valore non inizializzato in linea Finance. pm 135. L'utilizzo di valore non inizializzato in linea Finance. pm 133. L'utilizzo di valore non inizializzato in linea Finance. pm 135. L'utilizzo di valore non inizializzato a 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. Per una media mobile pesata lineare la formula per trovare il vettore dei pesi è: (1: n) sum (1: n) (in codice R). 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:40When working on the stock market, calculated indicators that include 28-day averages, 14-day averages, etc. need to be calculated. Furthermore every day the average needs to update to include the latest days closehighlowvolume. Now often the array needs to be looped through to find the sum, average, max, and min values. I though that a queue (in the form of a dynamic array or linked list or anything else you can think of) seems like the perfect data structure for this based on the FIFO method of entryexit. How does the efficiency and scalability of queues compare to hashes When running a Perl script the queue will not be in memory and will therefore have to be initialized and worked on (values initialized from a CSV file), I know this is pretty unrelated, but which data structure would be the best to use with a Perl script that executes on a daily schedule asked Feb 5 13 at 19:43 Not enough information here. Are you processing an entire days worth of quotes to get your daily highlowlast Are you doing the averages on a per instrument basis With any moving average, you can just use a list of values that make up the sum of the average. As a new value gets added, one drops off, and recalculate. So a hash of lists if your doing by instrument and calculate on the fly. I add a line to the CSV with closehighlow at the close of the day. the data is scraped from a feed. The averages are calculated per share, at the end of the day and inputted into a db. after which indicators are calculated using the values. Possibly an even better way to do it is to just save the 28th and 14th days close. then when updating (add new close to the old moving average and subtract the 28th 14th stored value. Wait I dunno ndash surfer190 Feb 5 13 at 20:55 user1439659 That works, and is more or less how you do it. Keep the sum, then do the addsubtractdivide. Just didn39t know how you were deriving the data. Things change when you have to rip through 1.5 billion records vs. having the closing values. ndash Mike Feb 5 13 at 21:10 What is most efficient really depends. Hashes are unordered. They can look up values in nearly-constant time by a string key. A lookup is computationally expensive, and at least an order of magnitude slower than an array lookup. How well a hash performs depends on the number of buckets and the number of keys. However, a hash lookup will be faster than looping through an array to find an element for all non-trivial cases. Hashes require more space than an array. Arrays in Perl have both the characteristics of an array (random access) and a doubly linked list (via push, pop, shift, unshift). They are easy to use, and fast enough. If more than one element is to be addedremoved, either use a slice, or the splice function. splice is a generalisation of push. unshift. and is faster than looping. Strings can be used to store an array of integers. This is extremely efficient, but also quite limited (only ints). Using Strings has the characteristics of an array (random access) and of a single linked list (appending is simple with . ). Other operations are reasonably fast as well ( substr has many uses). The pragmatic programmer will use arrays for most sequential data. He can also leverage the efficient functions from List::Util and List::MoreUtils that provide functions like sum. average. max and min (written in C for speed). When you are building a list of values, and only need a fixed amount, either do this when you add a new element: This is space-efficient but may be slower than simply building the list, and doing To access only a certain part of the array (without allocating a new variable), use slices: If you want to use hashes, but know all possible fields at compile time, you can define constant names for the fields, and use an array instead. So dont do When working with deeply nested data, it can sometimes pay off to cache nested references instead of recalculating them at every access: Hi thanks for your input. I think a singly linked list would be most efficient with FILO (first in, last out). PER ESEMPIO. I get the close for a particular day, that becomes head node of list, then the previous 28th falls off end of list and the moving average can be calculated again. Instead of inserting into a db, and calculating the 28 day moving average from there. Hang on that is the same thing. ndash surfer190 Feb 17 13 at 19:49 user1439659 That would be a FIFO, not a FILO. Don39t model FIFOs yourself (this is very inefficient), but use the builtin arrays. Those implement the characteristics of a double linked list. You will have to assert the fixed length yourself. See my first code example after quotuse arraysquot. Any way: premature optimization is the root of all evil. ndash amon Feb 17 13 at 20:06 If you are calculating these things once a day. use the easiest data structure to code Does it really take so much time to compute If yes, go on reading. The sum and average might be easier. If what you add are integers, you can use a FIFO and keep the sum in a variable. Whenever you insert or remove an element, update the sum accordingly (add or subtract). If you add floating point values, then the method described above might lead to cumulative errors. This might happen if the values are of very different magnitudes andor the series is very long. In this case, you would need something more complicated (see below). For the max and min, the most efficient data structures are maxmin-heaps. Note that you can embed them in arrays. You would need to have them cross-referenced with the elements of the FIFO queue in order to find immediately the element that has to be removed every time. The most general solution would be an augmented self-balanced tree. Augmented data structures are explained in chapter 14 of Introduction to Algorithms by Cormen, Leiserson, Rivest and Stein. Basically, the tree would contain one element of your data sequence in every node. Every node would contain also the sum, min and max of its subtree. Every time you update a node, you have to update the sum, max and min in all the path from that node to the root. in the root you have the global sum, max and min. You can find a C implementation of augmented self-balanced trees here . Though, since you only want the sum, min and max of a fixed number of elements, and you always insert at one end and remove at the other, you can make it much simpler. You only need a circular buffer and an array-embedded tree (see how to embed such tree in an array ). The tree would contain partial sum, min and max values, as in the augmented trees described before. The advantage is that you dont need to rebalance the tree because you never insertremove in the middle of the sequence, and the tree always has the same size. In order to have the statistics for the last 28 days, the last 14 days, the last week, and the last 3 days (for example), you would use a circular buffer and an array-embedded tree for every period: one for the last 3 days, another for the previous 4 (7 minus 3) days, another for the previous 7 days, and so on. Every day, you would take the last datum of every buffer and insert it in the next one. answered Feb 6 13 at 6:54 Thanks for your input. There are - 470 shares, about 10 calculations each. I haven39t tested but I think it may take significant time to compute. The easiest to code would be inserting records into db daily and computing from there. If I were to use some of the data structures you suggest, would it be feasible to store 470 of these data structures in memory for the whole day only to be updated once a day ndash surfer190 Feb 17 13 at 19:55 user1439659 There is only one way to find out (I don39t know the exact amount of data, the data structure, your OS, hardware, Perl compilation flags). The numbers you provide look reasonable even for low-powered machines, but I wouldn39t keep the data in memory all the time. It might be best to write working code, and then optimize for speed andor memory once you can test and profile working code. But no earlier. Premature optimization ndash amon Feb 17 13 at 20:26 I would just use a simple hash with keys being some stringified or numericized representation of the timestamp and the value being what your data is associated with that time series item. You can sort the keys of the hash, e. g. and loop through the last 28 or 14 etc. then retrieve the values from the hash.
No comments:
Post a Comment