Sunday 1 October 2017

Perl Ejemplo De Media Móvil


CONTENIDO Este capítulo le presenta los conceptos detrás de las referencias a módulos, paquetes y clases de Perl. También muestra cómo crear algunos módulos de ejemplo. Un módulo Perl es un conjunto de código Perl que actúa como una biblioteca de llamadas a funciones. El módulo de término en Perl es sinónimo del paquete de palabras. Los paquetes son una característica de Perl 4, mientras que los módulos son frecuentes en Perl 5. Puede mantener todo su código Perl reutilizable específico para un conjunto de tareas en un módulo Perl. Por lo tanto, toda la funcionalidad perteneciente a un tipo de tarea está contenida en un archivo. Es más fácil construir una aplicación en estos bloques modulares. Por lo tanto, el módulo de la palabra aplica un poco más que el paquete. Heres una introducción rápida a los módulos. Ciertos temas de esta sección se tratarán en detalle en el resto del libro. Lea los párrafos siguientes cuidadosamente para obtener una visión general de lo que está por venir mientras escribe y usa sus propios módulos. Lo que es confuso es que los términos módulo y paquete se utilizan indistintamente en toda la documentación de Perl, y estos dos términos significan lo mismo. Así que al leer documentos de Perl, sólo piensa en quotpackagequot cuando ves quotmodulequot y viceversa. Así que, ¿cuál es la premisa para el uso de módulos? Bueno, los módulos están ahí para empaquetar (perdonar el juego de palabras) variables, símbolos y elementos de datos interconectados juntos. Por ejemplo, usar variables globales con nombres muy comunes como k. J. O i en un programa generalmente no es una buena idea. También, un contador de bucle, i. Debe ser permitido trabajar independientemente en dos porciones diferentes del código. Declarar i como una variable global y luego incrementarla desde dentro de una subrutina creará problemas inmanejables con su código de aplicación porque la subrutina puede haber sido llamada desde dentro de un bucle que también usa una variable llamada i. El uso de módulos en Perl permite que las variables con el mismo nombre se creen en diferentes lugares distintos en el mismo programa. Los símbolos definidos para las variables se almacenan en una matriz asociativa, denominada tabla de símbolos. Estas tablas de símbolos son exclusivas de un paquete. Por lo tanto, las variables del mismo nombre en dos paquetes diferentes pueden tener valores diferentes. Cada módulo tiene su propia tabla de símbolos de todos los símbolos que se declaran dentro de él. La tabla de símbolos básicamente aísla nombres sinónimos en un módulo de otro. La tabla de símbolos define un espacio de nombres. Es decir, el uso de módulos, cada uno con su propia tabla de símbolos, impide que una variable declarada en una sección sobrescriba los valores de otras variables con el mismo nombre declarado en otra parte de la misma programa. De hecho, todas las variables en Perl pertenecen a un paquete. Las variables de un programa Perl pertenecen al paquete principal. Todos los demás paquetes dentro de un programa de Perl están anidados dentro de este paquete principal o existen al mismo nivel. Hay algunas variables verdaderamente globales, como la matriz SIG de manejadores de señales. Que están disponibles para todos los otros módulos en un programa de aplicación y no se pueden aislar a través de espacios de nombres. Sólo aquellos identificadores de variables que comienzan con letras o subrayado se mantienen en una tabla de símbolos de módulos. Todos los demás símbolos, como los nombres STDIN. STDOUT. STDERR. ARGV. ARGVOUT. ENV. Cª . Y SIG son obligados a estar en el paquete principal. Cambiar entre paquetes afecta sólo a los espacios de nombres. Todo lo que está haciendo cuando utiliza un paquete u otro es declarar qué tabla de símbolos se usará como tabla de símbolos predeterminada para buscar nombres de variables. Sólo las variables dinámicas se ven afectadas por el uso de tablas de símbolos. Las variables declaradas por el uso de la palabra clave my todavía se resuelven con el bloque de código en el que residen y no se hace referencia a través de tablas de símbolos. De hecho, el ámbito de una declaración de paquete permanece activo sólo dentro del bloque de código en el que se declara. Por lo tanto, si cambia tablas de símbolos mediante un paquete dentro de una subrutina, se restaurará la tabla de símbolos original en efecto cuando se realizó la llamada Cuando la subrutina regresa. Cambiar las tablas de símbolos sólo afecta a la búsqueda predeterminada de los nombres de las variables dinámicas. Todavía puede referirse explícitamente a variables, manejadores de archivos y así sucesivamente en un paquete específico preinstalando un nombre de paquete. Al nombre de la variable. Usted vio lo que era un contexto de paquete al usar referencias en el Capítulo 3. Un contexto de paquete simplemente implica el uso de la tabla de símbolos por el intérprete de Perl para resolver nombres de variables en un programa. Cambiando las tablas de símbolos, cambia el contexto del paquete. Los módulos se pueden anidar dentro de otros módulos. El módulo anidado puede utilizar las variables y funciones del módulo en el que está anidado. Para los módulos anidados, tendría que utilizar moduleName. NestedModuleName y así sucesivamente. Usando el doble colon (::) es sinónimo de usar una cita de retorno (). Sin embargo, el doble colon es la forma preferida de abordar las variables dentro de los módulos. El direccionamiento explícito de variables de módulo se realiza siempre con una referencia completa. Por ejemplo, supongamos que tiene un módulo, Inversión. Que es el paquete predeterminado en uso, y desea dirigirse a otro módulo, Bonds. Que está anidado dentro del módulo de inversión. En este caso, no puede utilizar Bond ::. En su lugar, tendría que utilizar Investment :: Bond :: para abordar variables y funciones dentro del módulo Bond. El uso de Bond :: implicaría el uso de un paquete Bond que está anidado dentro del módulo principal y no dentro del módulo de Inversión. La tabla de símbolos para un módulo se almacena realmente en una matriz asociativa de los nombres de módulos anexados con dos puntos. La tabla de símbolos de un módulo denominado Bond se denominará la matriz asociativa Bond ::. El nombre de la tabla de símbolos del módulo principal es main ::. E incluso se puede acortar a ::. Del mismo modo, todos los paquetes anidados tienen sus símbolos almacenados en matrices asociativas con dos puntos separados cada nivel de anidamiento. Por ejemplo, en el módulo Bond que está anidado dentro del módulo de inversión, la matriz asociativa para los símbolos del módulo Bond se denominará Investment :: Bond ::. Un typeglob es realmente un tipo global para un nombre de símbolo. Puede realizar operaciones de aliasing asignando a un typeglob. Una o más entradas en una matriz asociativa para símbolos se utilizarán cuando se utilice una asignación a través de un comando typeglob. El valor real en cada entrada de la matriz asociativa es a lo que se está refiriendo cuando se utiliza la notación variableName. Por lo tanto, hay dos maneras de referirse a los nombres de variables en un paquete: Inversión :: dinero Inversión :: cuentas En el primer método, se está refiriendo a las variables a través de una referencia typeglob. El uso de la tabla de símbolos, Investment ::. Está implícito aquí, y Perl optimizará la búsqueda de símbolos de dinero y facturas. Esta es la manera más rápida y preferida de abordar un símbolo. El segundo método utiliza una búsqueda para el valor de una variable dirigida por dinero y facturas en la matriz asociativa utilizada para los símbolos, Inversión :: explícitamente. Esta búsqueda se haría dinámicamente y no será optimizada por Perl. Por lo tanto, la búsqueda se verá obligado a comprobar la matriz asociativa cada vez que se ejecuta la instrucción. Como resultado, el segundo método no es eficiente y debe utilizarse sólo para demostrar cómo se implementa internamente la tabla de símbolos. Otro ejemplo en esta declaración kamran husain hace que variables, subrutinas y manejadores de archivos que se nombran a través del símbolo kamran sean también dirigidos a través del símbolo husain. Es decir, todas las entradas de símbolo en la tabla de símbolos actual con la clave kamran ahora contendrán referencias a los símbolos dirigidos por la clave husain. Para evitar dicha asignación global, puede utilizar referencias explícitas. Por ejemplo, la siguiente sentencia le permitirá abordar el contenido de husain a través de la variable kamran. Kamran husain Sin embargo, cualquier arrays como kamran y husain no será el mismo. Sólo se cambiarán las referencias especificadas explícitamente. Para resumir, cuando se asigna un typeglob a otro, se afectan todas las entradas en una tabla de símbolos independientemente del tipo de variable a la que se hace referencia. Cuando asigna una referencia de un tipo de variable a otro, sólo afecta a una entrada de la tabla de símbolos. Un archivo de módulo Perl tiene el siguiente formato: package ModuleName. Insertar el código del módulo. 1 El nombre de archivo debe llamarse ModuleName. pm. El nombre de un módulo debe terminar en la cadena. pm por convención. La instrucción del paquete es la primera línea del archivo. La última línea del archivo debe contener la línea con la instrucción 1. Esto en efecto devuelve un valor verdadero al programa de aplicación usando el módulo. No utilizar la instrucción 1 no permitirá que el módulo se cargue correctamente. La instrucción package le dice al intérprete de Perl que comience con un nuevo dominio de espacio de nombres. Básicamente, todas sus variables en un script Perl pertenecen a un paquete llamado main. Cada variable en el paquete principal se puede denominar mainvariable. Heres la sintaxis para tales referencias: packageNamevariableName La cita simple () es sinónimo del operador doble de dos puntos (::). Cubro más usos del operador :: en el próximo capítulo. Por el momento, debe recordar que las siguientes dos sentencias son equivalentes: packageNamevariableName packageName :: variableName La sintaxis de dos puntos se considera estándar en el mundo de Perl. Por lo tanto, para preservar la legibilidad, utilizo la sintaxis de dos puntos en el resto de este libro a menos que sea absolutamente necesario hacer excepciones para probar un punto. El uso predeterminado de un nombre de variable difiere al paquete actual activo en el momento de la compilación. Por lo tanto, si está en el paquete Finance. pm y especifique una variable pv. La variable es realmente igual a Finance :: pv. Uso de módulos Perl: use vs. require Incluya módulos Perl en su programa usando el uso o la instrucción require. Heres la manera de utilizar cualquiera de estas declaraciones: use ModuleName require ModuleName Observe que la extensión. pm no se usa en el código mostrado arriba. También tenga en cuenta que ninguna de las sentencias permite que un archivo se incluya más de una vez en un programa. El valor devuelto de true (1) como la última instrucción es necesario para permitir que Perl sepa que un módulo require d o use d se carga correctamente y permite que el intérprete Perl ignore cualquier recarga. En general, es mejor usar la instrucción Módulo de uso que la instrucción Module requerida en un programa Perl para seguir siendo compatible con versiones futuras de Perl. Para los módulos, es posible que desee considerar seguir utilizando la instrucción require. Heres why: La instrucción use hace un poco más de trabajo que la instrucción require en que altera el espacio de nombres del módulo que incluye otro módulo. Desea que esta actualización adicional del espacio de nombres se realice en un programa. Sin embargo, al escribir código para un módulo, es posible que no desee que el espacio de nombres se modifique a menos que sea explícitamente necesario. En este caso, utilizará la instrucción require. La instrucción require incluye la ruta de acceso completa de un archivo en la matriz Inc para que las funciones y variables en el archivo de módulos se encuentren en una ubicación conocida durante el tiempo de ejecución. Por lo tanto, las funciones que se importan de un módulo se importan a través de una referencia de módulo explícita en tiempo de ejecución con la instrucción require. La instrucción use hace lo mismo que la instrucción require porque actualiza la matriz Inc con nombres de ruta completos de módulos cargados. El código para la función de uso también va un paso más y llama a una función de importación en el módulo que se utiliza d para cargar explícitamente la lista de funciones exportadas en tiempo de compilación, ahorrando así el tiempo requerido para una resolución explícita de un nombre de función durante la ejecución. El uso de la instrucción use cambia el espacio de nombres de los programas porque los nombres de las funciones importadas se insertan en la tabla de símbolos. La instrucción require no altera el espacio de nombres de los programas. Por lo tanto, el siguiente uso de sentencia ModuleName () es equivalente a esta sentencia: require ModuleName Las funciones se importan de un módulo a través de una llamada a una función llamada import. Puede escribir su propia función de importación en un módulo, o puede utilizar el módulo Exportador y utilizar su función de importación. En casi todos los casos, utilizará el módulo Exportador para proporcionar una función de importación en lugar de reinventar la rueda. Si desea no utilizar el módulo Exportador, tendrá que escribir su propia función de importación en cada módulo que escriba. Es mucho más fácil simplemente usar el módulo Exportador y dejar Perl hacer el trabajo para usted. Módulo Sample Letter. pm La mejor manera de ilustrar la semántica de cómo se usa un módulo en Perl es escribir un módulo simple y mostrar cómo usarlo. Tomemos el ejemplo de un tiburón de préstamo local, Rudious Maximus, que simplemente está cansado de escribir el mismo quotrequest para cartas de pago. Al ser un ávido fan de las computadoras y Perl, Rudious toma el enfoque de los programadores perezosos y escribe un módulo Perl para ayudarle a generar sus memorandos y cartas. Ahora, en lugar de escribir dentro de los campos en un archivo de plantilla de memo, todo lo que tiene que hacer es escribir unas líneas para producir su nota agradable y amenazante. El Listado 4.1 le muestra lo que tiene que escribir. Listado 4.1. Uso del módulo Carta. 1 / usr / bin / perl - w 2 3 Descomente la línea de abajo para incluir el directorio actual en Inc. 4 push (Inc, pwd) 5 6 use Letter 7 8 Letter :: To (quotMr. Gambling Manquot, quotThe money for Lucky Perro, Raza 2quot) 9 Carta :: ClaimMoneyNice () 10 Letter :: ThankDem () 11 Letter :: Finish () La instrucción Letter de uso está presente para obligar al intérprete de Perl a incluir el código para el módulo en el programa de aplicación. El módulo debe ubicarse en el directorio / usr / lib / perl5 /, o puede colocarlo en cualquier directorio listado en la matriz Inc. La matriz Inc es la lista de directorios que el intérprete de Perl buscará al intentar cargar el código para el módulo nombrado. La línea comentada (número 4) muestra cómo agregar el directorio de trabajo actual para incluir la ruta. Las siguientes cuatro líneas del archivo generan el tema de la carta. Heres la salida de usar el módulo de la letra: A: Sr. Gambling Man Fm: Rudious Maximus, Shark del préstamo Dt: Mie Feb 7 10:35:51 CST 1996 Re: El dinero para el perro afortunado, raza 2 Ha venido a mi atención Que su cuenta está por encima de debido. Nos vas a pagar pronto o te gustaría que viniera ovah Gracias por tu apoyo. El archivo del módulo Carta se muestra en el listado 4.2. El nombre del paquete se declara en la primera línea. Debido a que las funciones de este módulo se exportan, yo uso el módulo Exportador. Por lo tanto, el uso de la instrucción Exportador debe heredar la funcionalidad del módulo Exportador. Otro paso necesario es poner la palabra exportada en la matriz ISA para permitir la búsqueda de Exported. pm. La matriz ISA es una matriz especial dentro de cada paquete. Cada elemento de la matriz muestra dónde buscar un método si no se encuentra en el paquete actual. El orden en el que los paquetes se enumeran en la matriz ISA es el orden en que Perl busca símbolos no resueltos. Una clase que se muestra en la matriz ISA se conoce como la clase base de esa clase en particular. Perl almacenará en caché los métodos faltantes encontrados en las clases base para futuras referencias. La modificación de la matriz ISA descargará la caché y hará que Perl vuelva a buscar todos los métodos. Veamos ahora el código de Letter. pm en el Listado 4.2. Listado 4.2. El módulo Letter. pm. 1 paquete Carta 2 3 requieren Exportador 4 ISA (exportador) 5 6 head1 NOMBRE 7 8 Carta - Módulo de muestra para generar encabezado para usted 9 10 head1 SINOPSIS 11 12 use Letter 13 14 Letter :: Date () 15 Letter :: To (name , La dirección de la empresa) 16 17 Una de las siguientes: 18 Carta :: ClaimMoneyNice () 19 Carta :: ClaimMoney () 20 Carta :: ThreatBreakLeg () 21 22 Carta :: ThankDem () 23 Letter :: Finish () 24 25 head1 DESCRIPCIÓN 26 27 Este módulo proporciona un breve ejemplo de la generación de una carta para un tiburón de préstamo agradable de vecino. 29 30 El código comienza después de la sentencia quotcutquot. 31 corte 32 33 EXPORTACIÓN qw (Fecha, 34 A, 35 ReclamaciónMoney, 36 ReclamaciónMoneyNice, 37 Agradecimiento, 38 Finalización) 39 40 41 Impresión de la fecha de hoy 42 43 sub Letra :: Fecha 44 fecha fecha 45 impresión quotn Hoy es la fecha 46 47 48 sub Letra :: A 49 cambio local (nombre) 50 cambio local (sujeto) 51 impresión quotn A: nombrequot 52 impresión quotn Fm: Rudious Maximus, Préstamo Sharkquot 53 impresión quotn Dt: quot, fecha 54 impresión quotn Re: subjectquot 55 print quotnnquot 56 Print quotnnquot 57 58 sub Letra :: ClaimMoney () 59 print quotn Me debes dinero. ¿Quieres que envíe a Bruno a quot 61 imprimir quotn recogerlo. O vas a pagar 62 63 64 sub Letra :: ClaimMoneyNice () 65 impresión quotn Se ha llegado a mi atención que su cuenta es quotn 66 impresión quotn camino más de due. quot 67 impresión quotn Usted va a pagar pronto ... 68 Imprimir quotn o le gustaría que me vienen ovahquot 69 70 71 sub Letter :: ThreatBreakLeg () 72 imprimir quotn aparentemente cartas como estas no helpquot 73 imprimir quotn Voy a tener que hacer un ejemplo de youquot 74 imprimir quotn n Nos vemos en el hospital , Palquot 75 76 77 sub Letra :: ThankDem () 78 print quotnn Gracias por su apoyo 79 80 81 sub Letter :: Finish () 82 printf quotnnnn Sinceramentequot 83 printf quotn Rudious n quot 84 85 86 1 Se utilizan líneas que contienen el signo de igual Para la documentación. Debe documentar cada módulo para su propia referencia Los módulos Perl no necesitan ser documentados, pero es una buena idea escribir algunas líneas sobre lo que hace su código. Dentro de unos años, usted puede olvidar lo que es un módulo. Una buena documentación es siempre una necesidad si desea recordar lo que hizo en el pasado. Cubro los estilos de documentación utilizados para Perl en el capítulo 8. quotDocumenting Perl Scripts. quot Para este módulo de ejemplo, la instrucción head1 comienza la documentación. El intérprete de Perl ignora todo hasta la sentencia de corte. A continuación, el módulo enumera todas las funciones exportadas por este módulo en la matriz EXPORT. La matriz EXPORT define todos los nombres de funciones que pueden ser llamados por código externo. Si no se lista una función en esta matriz EXPORT, no será visto por módulos de código externos. Después de la matriz EXPORT es el cuerpo del código, una subrutina a la vez. Después de definir todas las subrutinas, la instrucción final 1 termina el archivo de módulo. 1 debe ser la última línea ejecutable en el archivo. Veamos algunas de las funciones definidas en este módulo. La primera función a observar es la simple función de fecha, líneas 43 a 46, que imprime la fecha y la hora actuales de UNIX. No hay parámetros para esta función, y no devuelve nada significativo a la persona que llama. Tenga en cuenta el uso de mi antes de la variable de fecha en la línea 44. La palabra clave mi se utiliza para limitar el alcance de la variable a dentro de las funciones de fecha rizadores. El código entre llaves se refiere como un bloque. Las variables declaradas dentro de un bloque tienen un alcance limitado dentro de las llaves. En 49 y 50, el nombre de las variables locales y el sujeto son visibles para todas las funciones. También puede declarar variables con el calificador local. El uso de local permite que una variable esté en alcance para el bloque actual así como para otros bloques de código llamados desde dentro de este bloque. Así, una x local declarada dentro de un bloque es visible para todos los bloques subsiguientes llamados desde dentro de este bloque y puede ser referenciado. En el siguiente código de ejemplo, se puede acceder a la variable de nombre de funciones ToTitled pero no a los datos en iphone. 1 sub Letter :: ToTitled 2 local (nombre) shift 3 my (phone) shift El código de ejemplo para Letter. pm mostró cómo extraer un parámetro a la vez. La subrutina To () toma dos parámetros para configurar el encabezado para el memo. El uso de funciones dentro de un módulo no es diferente de usar y definir módulos Perl dentro del mismo archivo de código. Los parámetros se pasan por referencia a menos que se especifique lo contrario. Múltiples matrices pasan a una subrutina, si no se desreferencia explícitamente usando la barra invertida, se concatenan. La matriz de entrada en una función es siempre una matriz de valores escalares. Pasar valores por referencia es la forma preferida en Perl para pasar una gran cantidad de datos a una subrutina. (Véase el capítulo 3. quotReferences. quot) Otro Módulo de Muestra: Finanzas El módulo de Finanzas, que se muestra en el Listado 4.3, se utiliza para proporcionar cálculos simples para los valores del préstamo. Usar el módulo de Finanzas es sencillo. Todas las funciones se escriben con los mismos parámetros, como se muestra en la fórmula para las funciones. Veamos cómo se puede calcular el valor futuro de una inversión. Por ejemplo, si usted invierte algunos dólares, pv. En un bono que ofrece un porcentaje fijo, r. Aplicada a intervalos conocidos durante n periodos de tiempo, cuál es el valor del enlace en el momento de su vencimiento En este caso, usará la siguiente fórmula: fv pv (1r) n La función para obtener el valor futuro se declara como FutureValue . Consulte el Listado 4.3 para ver cómo usarlo. Listado 4.3. Uso del módulo Finanzas. 1 / usr / bin / perl - w 2 3 push (Inc, pwd) 4 uso Finanzas 5 6 préstamo 5000.00 7 abr 3.5 APR 8 año 10 en años. 9 10 ------------------------------------------------ ---------------- 11 Calcule el valor al final del préstamo si se aplican intereses 12 cada año. 13 ------------------------------------------------- --------------- 14 año de tiempo 15 fv1 Finanzas :: FutureValue (préstamo, abril, tiempo) 16 print quotn Si se aplica interés al final del año 17 print quotn El valor futuro para un Préstamo de quot. préstamo. Quotnquot 18 print quot en una APR de quot, abr. Quot for quot, time, quot yearsquot 19 printf quot is 8.2f nquot. Fv1 20 21 ----------------------------------------------- ----------------- 22 Calcule el valor al final del préstamo si el interés 23 se aplica cada mes. 24 ------------------------------------------------- --------------- 25 tasa apr / 12 APR 26 tiempo año 12 en meses 27 fv2 Finanzas :: FutureValue (préstamo, tasa, tiempo) 28 29 imprimir quotn Si se aplica interés al final De cada mesquot 30 print quotn El valor futuro para un préstamo de quotn. préstamo. Quotnquot 31 print quot en una APR de quot, abr. Quot for quot, time, quot monthsquot 32 printf quot is 8.2f nquot. Fv2 33 34 printf quotn La diferencia de valor es 8.2fquot, fv2 - fv1 35 printf quotn Por lo tanto, al aplicar el interés en periodos de tiempo más cortos en 36 printf quotn en realidad estamos recibiendo más dinero en interest. nquot Aquí está la muestra de entrada y salida del Listado 4.3. Testme Si el interés se aplica al final del año El valor futuro para un préstamo de 5000 a una TAE de 3,5 por 10 años es 7052.99 Si se aplica el interés al final de cada mes El valor futuro para un préstamo de 5000 a una TAE de 3,5 para 120 meses es 7091.72 La diferencia en el valor es 38.73 Por lo tanto, al aplicar el interés en períodos de tiempo más cortos que realmente están recibiendo más dinero en interés. La revelación en la salida es el resultado de la comparación de valores entre fv1 y fv2. El valor fv1 se calcula con la aplicación de intereses una vez al año durante la vida del bono. Fv2 es el valor si el interés se aplica cada mes al tipo de interés mensual equivalente. El paquete Finance. pm se muestra en el listado 4.4 en sus primeras etapas de desarrollo. Listado 4.4. El paquete Finance. pm. 1 paquete Finanzas 2 3 requieren Exportador 4 ISA (Exportador) 5 6 head1 Finance. pm 7 8 Calculadora financiera - Cálculos financieros simplificados con Perl 9 10 cabeza 2 11 uso Finanzas 12 13 pv 10000.0 14 15 tasa 12.5 / 12 APR por mes. 16 17 tiempo 360 meses para que el préstamo madure 18 19 fv FutureValue () 20 21 impresión fv 22 23 recorte 24 25 EXPORTACIÓN qw (FutureValue, 26 PresentValue, 27 FVofAnnuity, 28 AnnuityOfFV, 29 getLastAverage, 30 getMovingAverage, 31 SetInterest) 32 33 34 Globals, si hay alguno 35 36 37 default localInterest 5.0 38 39 sub Finanzas :: SetInterest () 40 mi cambio de velocidad () 41 defaultTest de interés 42 printf quotn defaultInterest ratequot 43 44 45 -------------- -------------------------------------------------- ---- 46 Notas: 47 1. El tipo de interés r se da en un valor de 0-100. 48 2. El n dado en los términos es la tasa a la que se aplica el interés 49. 50 51 ------------------------------------------------ -------------------- 52 53 ---------------------------- ---------------------------------------- 54 Valor presente de una inversión dada 55 fv - Un valor futuro 56 r - tasa por período 57 n - número de período 58 ---------------------------------- ---------------------------------- 59 sub Finanzas :: FutureValue () 60 my (pv, r, n ) 61 mi fv pv ((1 (r / 100)) n) 62 retorno fv 63 64 65 ---------------------------- ---------------------------------------- 66 Valor presente de una inversión dada 67 fv - Un valor futuro 68 r - tasa por período 69 n - número del período 70 ---------------------------------- ---------------------------------- 71 sub Finanzas :: PresentValue () 72 mi pv 73 mi (fv, R, n) 74 pv fv / ((1 (r / 100)) n) 75 pv de retorno 76 77 78 79 ------------------------ -------------------------------------------- 80 Obtenga el valor futuro de Una anualidad dada 81 mp - Pago Mensual de Anualidad 82 r - tasa por período 83 n - número del período 84 --------------------------- ----------------------------------------- 85 86 sub FVofAnnuity () 87 mi fv 88 mi unoR 89 mi (mp, r, n) 90 91 unR (1 r) n 92 fv mp ((unoR - 1) / r) 93 retorno fv 94 95 96 ------------ -------------------------------------------------- ------ 97 Obtener la anualidad de los siguientes bits de información 98 r - tasa por período 99 n - número de período 100 fv - Valor futuro 101 ---------------- -------------------------------------------------- - 102 103 sub AnnuityOfFV () 104 mi mp mp - Pago mensual de la anualidad 105 mi unoR 106 mi (fv, r, n) 107 108 unR (1 r) n 109 mp fv (r / (unoR - 1)) 110 Return mp 111 112 113 --------------------------------------------- ----------------------- 114 Obtenga el promedio de los últimos valores quotnquot en una matriz. 115 ------------------------------------------------- ------------------- 116 El último número de cuenta de elementos de la matriz en valores 117 El número total de elementos en valores está en número 118 119 sub getLastAverage () 120 my (Recuento, número, valores) 121 my i 122 123 my a 0 124 return 0 si (count 0) 125 para (i 0 ilt count i) 126 a valoresnumber - i - 1 127 128 return a / count 129 130 131 - -------------------------------------------------- ---------------- 132 Obtener una media móvil de los valores. 133 ------------------------------------------------- ------------------- 134 El tamaño de la ventana es el primer parámetro, el número de elementos en la matriz pasada 135 es el siguiente. (Esto se puede calcular fácilmente dentro de la función 136 usando la función scalar (), pero la subrutina mostrada aquí 137 también se está usando para ilustrar cómo pasar los punteros.) La referencia a la matriz de valores 138 se pasa después, seguida por una Referencia al lugar en el que se almacenarán los valores de retorno. 140 141 sub getMovingAve () 142 mi (cuenta, número, valores, movingAve) 143 mi i 144 mi a 0 145 mi v 0 146 147 devuelve 0 si (cuenta 0) (Contando lt 2) 150 151 moviendoAve0 0 152 moviendoAveno - 1 0 153 para (i0 iltcounti) 154 v valuesi 155 av / count 156 movingAvei 0 157 158 para (icountnumero) 159 v valuesi 160 av / count 161 v valuesi - Count - 1 162 a - v / count 163 movingAvei a 164 165 return 0 166 167 168 1 Consulte la declaración de la función FutureValue con (). Los signos de tres dólares juntos significan tres números escalares que pasan a la función. Este escopo extra está presente para validar el tipo de parámetros pasados ​​a la función. Si tuvieras que pasar una cadena en lugar de un número en la función, obtendrías un mensaje muy similar a éste: Demasiados argumentos para Finance :: FutureValue en ./f4.pl línea 15, cerca de quottime) quot Ejecución de. /f4.pl abortado debido a errores de compilación. El uso de prototipos al definir funciones impide enviar valores distintos de los que la función espera. Utilice o para pasar en una matriz de valores. Si está pasando por referencia, use o para mostrar una referencia escalar a una matriz o hash, respectivamente. Si no utiliza la barra invertida, se ignoran todos los demás tipos del prototipo de la lista de argumentos. Otros tipos de descalificadores incluyen un esperma para una referencia a una función, un asterisco para cualquier tipo y un punto y coma para indicar que todos los demás parámetros son opcionales. Ahora, veamos la declaración de la función lastMovingAverage, que especifica dos enteros en el frente seguido de una matriz. La forma en que se usan los argumentos en la función es asignar un valor a cada uno de los dos escalares, count y number. Mientras que todo lo demás se envía a la matriz. Observe la función getMovingAverage () para ver cómo se pasan dos matrices para obtener el promedio móvil en una lista de valores. La forma de llamar a la función getMovingAverage se muestra en el Listado 4.5. Listado 4.5. Uso de la función de promedio móvil. 1 / usr / bin / perl - w 2 3 push (Inc, pwd) 4 uso Finanzas 5 6 valores (12,22,23,24,21,23,24,23,23,21,29,27,26, 28) 7 mv (0) 8 tamaño escalar (valores) 9 print quotn Valores para trabajar con nquot 10 print quot Número de valores size nquot 11 12 ------------------- --------------------------------------------- 13 Calcular el promedio de La función anterior 14 ---------------------------------------------- ------------------ 15 ave Finanzas :: getLastAverage (5, size, values) 16 print quotn Promedio de los últimos 5 días ave nquot 17 18 Finanzas :: getMovingAve (5, Tamaño, valores, mv) 19 print quotn Promedio móvil con ventana de 5 días n nquot Heres la salida del listado 4.5: Valores para trabajar con Número de valores 14 Promedio de los últimos 5 días 26.2 La función getMovingAverage () toma dos escalares y luego dos referencias A arreglos como escalares. Dentro de la función, los dos escalares a las matrices son dereferenced para el uso como arrays numéricos. El conjunto de valores devueltos se inserta en el área pasada como segunda referencia. Si los parámetros de entrada no se hubieran especificado con cada matriz referenciada, la referencia del array movingAve estaría vacía y habría causado errores en tiempo de ejecución. En otras palabras, la siguiente declaración no es correcta: sub getMovingAve () El resultado de los mensajes de error de un prototipo de función incorrecta es el siguiente: Uso del valor no inicializado en la línea Finance. pm 128. Uso del valor no inicializado en la línea Finance. pm 128. Uso del valor no inicializado en Finance. pm línea 128. Uso del valor no inicializado en Finance. pm línea 128. Uso del valor no inicializado en Finance. pm línea 128. Uso del valor no inicializado en Finance. pm línea 133. Uso de valor no inicializado En Finance. pm línea 135. Uso del valor no inicializado en Finance. pm línea 133. Uso del valor no inicializado en Finance. pm línea 135. Uso del valor no inicializado en Finance. pm línea 133. Uso de uninitialized valor en Finance. pm línea 135 Uso del valor no inicializado en Finance. pm línea 133. Uso del valor no inicializado en Finance. pm línea 135. Uso del valor no inicializado en Finance. pm línea 133. Uso del valor no inicializado en Finance. pm línea 135. Uso de valor no inicializado en 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 /usr/bin/perl - 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 ./SuperClass/NextSubClass/133 . 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 /usr/lib/perl5 directory: Create a Money directory under the /usr/lib/perl5 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 /usr/lib/perl5 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 /usr/bin/perl - w 2 aa pwd 3 aa . quot/Moneyquot 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 /usr/lib/perl5/lib 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 /usr/lib/perl5 directory to your path.) find /usr/lib/perl5 - 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.The 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 and/or 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, 2/3, 1/2, 2/5, 1/3, 2/7, and 1/4. The values 1, 1/2, and 2/5 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. 1/2 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 2/5 (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 . Fail Fast 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. Footnotes Quality Software Management: Vol. 1 Systems Thinking . Gerald Weinberg, Dorset House, 1991, p. 236. Part of the Test-Simple distribution, available at search. cpan. org/searchqueryTest-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. Averages/Simple moving average Averages/Simple moving average You are encouraged to solve this task according to the task description, using any language you may know. Computing the simple moving average of a series of numbers. Create a stateful function/class/instance that takes a period and returns a routine that takes a number as argument and returns a simple moving average of its arguments so far. A simple moving average is a method for computing an average of a stream of numbers by only averaging the last 160 P 160 numbers from the stream, 160 where 160 P 160 is known as the period. It can be implemented by calling an initialing routine with 160 P 160 as its argument, 160 I(P), 160 which should then return a routine that when called with individual, successive members of a stream of numbers, computes the mean of (up to), the last 160 P 160 of them, lets call this 160 SMA(). The word 160 stateful 160 in the task description refers to the need for 160 SMA() 160 to remember certain information between calls to it: 160 The period, 160 P 160 An ordered container of at least the last 160 P 160 numbers from each of its individual calls. Stateful 160 also means that successive calls to 160 I(), 160 the initializer, 160 should return separate routines that do 160 not 160 share saved state so they could be used on two independent streams of data. Pseudo-code for an implementation of 160 SMA 160 is: This version uses a persistent queue to hold the most recent p values. Each function returned from init-moving-average has its state in an atom holding a queue value. This implementation uses a circular list to store the numbers within the window at the beginning of each iteration pointer refers to the list cell which holds the value just moving out of the window and to be replaced with the just-added value. Using a Closure edit Currently this sma cant be nogc because it allocates a closure on the heap. Some escape analysis could remove the heap allocation. Using a Struct edit This version avoids the heap allocation of the closure keeping the data in the stack frame of the main function. Same output: To avoid the floating point approximations keep piling up and growing, the code could perform a periodic sum on the whole circular queue array. This implementation produces two (function) objects sharing state. It is idiomatic in E to separate input from output (read from write) rather than combining them into one object. The structure is the same as the implementation of Standard DeviationE. The elixir program below generates an anonymous function with an embedded period p, which is used as the period of the simple moving average. The run function reads numeric input and passes it to the newly created anonymous function, and then inspects the result to STDOUT. The output is shown below, with the average, followed by the grouped input, forming the basis of each moving average. Erlang has closures, but immutable variables. A solution then is to use processes and a simple message passing based API. Matrix languages have routines to compute the gliding avarages for a given sequence of items. It is less efficient to loop as in the following commands. Continuously prompts for an input I . which is added to the end of a list L1 . L1 can be found by pressing 2ND/1, and mean can be found in List/OPS Press ON to terminate the program. Function that returns a list containing the averaged data of the supplied argument Program that returns a simple value at each invocation: list is the list being averaged: p is the period: 5 returns the averaged list: Example 2: Using the program movinav2(i,5) - Initializing moving average calculation, and define period of 5 movinav2(3, x):x - new data in the list (value 3), and result will be stored on variable x, and displayed movinav2(4, x):x - new data (value 4), and the new result will be stored on variable x, and displayed (43)/2 . Description of the function movinavg: variable r - is the result (the averaged list) that will be returned variable i - is the index variable, and it points to the end of the sub-list the list being averaged. variable z - an helper variable The function uses variable i to determine which values of the list will be considered in the next average calculation. At every iteration, variable i points to the last value in the list that will be used in the average calculation. So we only need to figure out which will be the first value in the list. Usually well have to consider p elements, so the first element will be the one indexed by (i-p1). However on the first iterations that calculation will usually be negative, so the following equation will avoid negative indexes: max(i-p1,1) or, arranging the equation, max(i-p,0)1. But the number of elements on the first iterations will also be smaller, the correct value will be (end index - begin index 1) or, arranging the equation, (i - (max(i-p,0)1) 1),and then, (i-max(i-p,0)). Variable z holds the common value (max(i-p),0) so the beginindex will be (z1) and the numberofelements will be (i-z) mid(list, z1, i-z) will return the list of value that will be averaged sum(. ) will sum them sum(. )/(i-z) ri will average them and store the result in the appropriate place in the result list Using a closure and creating a function

No comments:

Post a Comment