Tuesday 27 June 2017

Perl Moving Average Function


Este capítulo apresenta os conceitos por trás das referências aos módulos Perl, pacotes e aulas. Ele também mostra como criar alguns módulos de amostra. Um módulo Perl é um conjunto de código Perl que funciona como uma biblioteca de chamadas de função. O termo módulo em Perl é sinônimo da palavra pacote. Os pacotes são uma característica do Perl 4, enquanto os módulos são prevalentes no Perl 5. Você pode manter todo seu código Perl reutilizável específico para um conjunto de tarefas em um módulo Perl. Portanto, todas as funcionalidades pertencentes a um tipo de tarefa estão contidas em um arquivo. É mais fácil criar uma aplicação nesses blocos modulares. Portanto, o módulo da palavra aplica um pouco mais do que o pacote. Heres uma introdução rápida aos módulos. Certos tópicos nesta seção serão abordados em detalhes ao longo do resto do livro. Leia atentamente os seguintes parágrafos para obter uma visão geral sobre o que está por vir enquanto escreve e usa seus próprios módulos. O que é confuso é que os termos módulo e pacote são usados ​​indistintamente em toda a documentação Perl, e estes dois termos significam a mesma coisa. Então, ao ler documentos Perl, basta pensar em quotpackagequot quando você vê quotmodulequot e vice-versa. Então, qual é a premissa para o uso de módulos Bem, os módulos estão lá para empacotar (desculpar as palavras), símbolos e itens de dados interligados em conjunto. Por exemplo, usando variáveis ​​globais com nomes muito comuns, como k. J. Ou eu em um programa geralmente não é uma boa idéia. Além disso, um contador de contatos, eu. Deve ser permitido trabalhar de forma independente em duas porções diferentes do código. Declarar i como uma variável global e, em seguida, incrementá-lo dentro de uma sub-rotina criará problemas impossíveis de gerenciar com seu código de aplicativo porque a sub-rotina pode ter sido chamada de dentro de um ciclo que também usa uma variável chamada i. O uso de módulos no Perl permite que variáveis ​​com o mesmo nome sejam criadas em locais diferentes e distintos no mesmo programa. Os símbolos definidos para suas variáveis ​​são armazenados em uma matriz associativa, referida como uma tabela de símbolos. Essas tabelas de símbolos são exclusivas de um pacote. Portanto, as variáveis ​​do mesmo nome em dois pacotes diferentes podem ter valores diferentes. Cada módulo possui sua própria tabela de símbolos de todos os símbolos que são declarados dentro dele. A tabela de símbolos basicamente isola nomes sinônimos em um módulo de outro. A tabela de símbolos define um namespace. Isto é, um espaço para nomes de variáveis ​​independentes existe. Assim, o uso de módulos, cada um com sua própria tabela de símbolos, evita que uma variável declarada em uma seção sobrescreva os valores de outras variáveis ​​com o mesmo nome declarado em outro lugar no mesmo programa. De fato, todas as variáveis ​​em Perl pertencem a um pacote. As variáveis ​​em um programa Perl pertencem ao pacote principal. Todos os outros pacotes dentro de um programa Perl são aninhados dentro deste pacote principal ou existem no mesmo nível. Existem algumas variáveis ​​verdadeiramente globais, como a matriz de manipuladores de sinal SIG. Que estão disponíveis para todos os outros módulos em um programa aplicativo e não podem ser isolados por espaços de nome. Apenas os identificadores de variáveis ​​que começam com letras ou um sublinhado são mantidos em uma tabela de símbolos de módulos. Todos os outros símbolos, como os nomes STDIN. STDOUT. STDERR. ARGV. ARGVOUT. ENV. Inc. E SIG são obrigados a estar no pacote principal. Alternar entre pacotes afeta apenas namespaces. Tudo o que você está fazendo quando usa um pacote ou outro é declarar qual tabela de símbolos usar como a tabela de símbolos padrão para pesquisa de nomes de variáveis. Somente variáveis ​​dinâmicas são afetadas pelo uso de tabelas de símbolos. As variáveis ​​declaradas pelo uso da minha palavra-chave ainda são resolvidas com o bloco de código em que elas residem e não são referenciadas através de tabelas de símbolos. De fato, o escopo de uma declaração de pacote permanece ativo apenas dentro do bloco de código em que é declarado. Portanto, se você alternar tabelas de símbolos usando um pacote dentro de uma sub-rotina, a tabela de símbolos original em vigor quando a chamada for feita será restaurada Quando a sub-rotina retorna. Alterar tabelas de símbolos afeta apenas a pesquisa padrão de nomes de variáveis ​​dinâmicas. Você ainda pode se referir explicitamente a variáveis, alças de arquivo, e assim por diante em um pacote específico, antecipando um pacoteName. Para o nome da variável. Você viu o que era um contexto de pacote ao usar referências no Capítulo 3. Um contexto de pacote simplesmente implica o uso da tabela de símbolos pelo intérprete de Perl para resolver nomes de variáveis ​​em um programa. Ao mudar as tabelas de símbolos, você está alternando o contexto do pacote. Os módulos podem ser aninhados em outros módulos. O módulo aninhado pode usar as variáveis ​​e funções do módulo em que está aninhado. Para módulos aninhados, você precisaria usar moduleName. AninhadoModuleName e assim por diante. Usar o duplo colo (::) é sinônimo de usar uma cotação anterior (). No entanto, o cólon duplo é a maneira preferida e futura de abordar variáveis ​​dentro dos módulos. O endereçamento explícito das variáveis ​​do módulo sempre é feito com uma referência completa. Por exemplo, suponha que você tenha um módulo, Investimento. Qual é o pacote padrão em uso, e você deseja endereçar outro módulo, Bonds. Que está aninhado no módulo Investimento. Nesse caso, você não pode usar Bond ::. Em vez disso, você precisaria usar o Investment :: Bond :: para abordar variáveis ​​e funções dentro do módulo Bond. Usando Bond :: implicaria o uso de um pacote Bond que está aninhado dentro do módulo principal e não dentro do módulo de Investimento. A tabela de símbolos para um módulo é realmente armazenada em uma matriz associativa dos nomes dos módulos anexados com dois pontos. A tabela de símbolos para um módulo chamado Bond será referida como a matriz associativa Bond ::. O nome da tabela de símbolos para o módulo principal é main ::. E pode até ser encurtado para ::. Da mesma forma, todos os pacotes aninhados têm seus símbolos armazenados em matrizes associativas com dois pontos separados por cada nível de nidificação. Por exemplo, no módulo Bond que está aninhado no módulo Investment, a matriz associativa para os símbolos no módulo Bond será denominada Investment :: Bond ::. Um typeglob é realmente um tipo global para um nome de símbolo. Você pode executar operações de aliasing atribuindo a um typeglob. Uma ou mais entradas em uma matriz associativa para símbolos serão usadas quando uma atribuição através de um typeglob é usada. O valor real em cada entrada da matriz associativa é o que você está se referindo ao usar a notação do nome da variável. Assim, existem duas maneiras de se referir a nomes de variáveis ​​em um pacote: Investimento :: dinheiro Investimento :: contas No primeiro método, você está se referindo às variáveis ​​através de uma referência typeglob. O uso da tabela de símbolos, Investment ::. Está implícito aqui, e Perl irá otimizar a pesquisa de símbolos de dinheiro e contas. Esta é a maneira mais rápida e preferida de endereçar um símbolo. O segundo método usa uma pesquisa para o valor de uma variável endereçada por dinheiro e contas na matriz associativa usada para símbolos, Investimento :: explicitamente. Essa pesquisa seria feita dinamicamente e não será otimizada pela Perl. Portanto, a pesquisa será forçada a verificar a matriz associativa sempre que a instrução for executada. Como resultado, o segundo método não é eficiente e deve ser usado apenas para demonstração de como a tabela de símbolos é implementada internamente. Outro exemplo nesta afirmação kamran husain provoca variáveis, sub-rotinas e identificadores de arquivo que são nomeados através do símbolo kamran para também ser direcionado através do símbolo de um dono. Ou seja, todas as entradas de símbolos na tabela de símbolos atual com a chave kamran agora conterão referências aos símbolos abordados pelo caderno-chave. Para evitar tal atribuição global, você pode usar referências explícitas. Por exemplo, a seguinte afirmação permitirá que você aborde o conteúdo do site por meio da variável kamran. Kamran husain No entanto, qualquer arrays como kamran e husain não serão os mesmos. Somente o que as referências especificadas explicitamente serão alteradas. Para resumir, quando você atribui um typeglob a outro, você afeta todas as entradas em uma tabela de símbolos independentemente do tipo de variável a que se refere. Quando você atribui uma referência de um tipo de variável para outro, você está afetando apenas uma entrada na tabela de símbolos. Um arquivo de módulo Perl possui o seguinte formato: package ModuleName. Insira o código do módulo. 1 O nome do arquivo deve ser chamado ModuleName. pm. O nome de um módulo deve terminar na string. pm por convenção. A declaração do pacote é a primeira linha do arquivo. A última linha do arquivo deve conter a linha com a declaração 1. Isso, de fato, retorna um valor verdadeiro para o programa aplicativo usando o módulo. Não usar a declaração 1 não permitirá que o módulo seja carregado corretamente. A declaração do pacote informa ao intérprete Perl para começar com um novo domínio do namespace. Basicamente, todas as suas variáveis ​​em um script Perl pertencem a um pacote chamado main. Toda variável no pacote principal pode ser referida como mainvariable. Heres a sintaxe para tais referências: packageNamevariableName A citação única () é sinônimo do operador dobro do dois-pontos (::). Eu cobrei mais usos do :: operador no próximo capítulo. Por enquanto, você deve lembrar que as duas instruções a seguir são equivalentes: packageNamevariableName packageName :: variableName A sintaxe do duplo-cólon é considerada padrão no mundo Perl. Portanto, para preservar a legibilidade, uso a sintaxe de dois-cóculos no resto deste livro, a menos que seja absolutamente necessário fazer exceções para provar um ponto. O uso padrão de um nome de variável difere para o pacote atual ativo no momento da compilação. Assim, se você estiver no pacote Finance. pm e especifique uma variável pv. A variável é na verdade igual a Finanças :: pv. Usando Módulos Perl: use vs. require Você inclui módulos Perl em seu programa usando a declaração de uso ou exigir. Existe a maneira de usar qualquer uma dessas instruções: use ModuleName require ModuleName. Observe que a extensão. pm não é usada no código mostrado acima. Observe também que nenhuma das instruções permite que um arquivo seja incluído mais de uma vez em um programa. O valor retornado de true (1) como a última declaração é necessário para permitir que Perl saiba que um módulo d requer ou d é carregado corretamente e permite que o intérprete Perl ignore qualquer recarga. Em geral, é melhor usar a instrução Módulo de uso do que a instrução requerida do Módulo em um programa Perl para permanecer compatível com futuras versões do Perl. Para módulos, você pode querer considerar continuar a usar a instrução exigida. Heres por que: A declaração de uso faz um pouco mais de trabalho do que a instrução exigida na medida em que altera o namespace do módulo que inclui outro módulo. Você deseja que esta atualização adicional do namespace seja feita em um programa. No entanto, ao escrever código para um módulo, você pode não querer que o namespace seja alterado a menos que seja explicitamente necessário. Nesse caso, você usará a declaração obrigatória. A instrução exigir inclui o nome de caminho completo de um arquivo na matriz Inc para que as funções e variáveis ​​no arquivo de módulos estejam em um local conhecido durante o tempo de execução. Portanto, as funções que são importadas de um módulo são importadas através de uma referência de módulo explícita em tempo de execução com a instrução exigida. A declaração de uso faz a mesma coisa que a instrução exigida porque atualiza a matriz Inc com os nomes de caminho completos dos módulos carregados. O código para a função de uso também vai um passo adiante e chama uma função de importação no módulo que está sendo usado d para carregar explicitamente a lista de funções exportadas em tempo de compilação, economizando o tempo necessário para uma resolução explícita de um nome de função durante a execução. Basicamente, a indicação de uso é equivalente a exigir a importação do Nome do módulo Lista do Módulo das funções importadas O uso da declaração de uso altera o namespace de seus programas porque os nomes das funções importadas são inseridos na tabela de símbolos. A declaração exigida não altera o espaço para nome de seus programas. Portanto, a seguinte instrução usa ModuleName () é equivalente a esta declaração: require ModuleName As funções são importadas de um módulo via uma chamada para uma função chamada importação. Você pode escrever sua própria função de importação em um módulo, ou pode usar o módulo Exportador e usar sua função de importação. Em quase todos os casos, você usará o módulo Exportador para fornecer uma função de importação em vez de reinventar a roda. (Você aprenderá mais sobre isso na próxima seção.) Se você decidir não usar o módulo Exportador, você terá que escrever sua própria função de importação em cada módulo que você escreva. É muito mais fácil simplesmente usar o módulo Exportador e permitir que Perl faça o trabalho para você. O Módulo Sample Letter. pm A melhor maneira de ilustrar a semântica de como um módulo é usado no Perl é escrever um módulo simples e mostrar como usá-lo. Vamos tomar o exemplo de um tubarão de empréstimo local, Rudious Maximus, que simplesmente está cansado de digitar o mesmo pedido para cartas de pagamento. Sendo um ávido fã de computadores e Perl, Rudious leva os programadores preguiçosos e escreve um módulo Perl para ajudá-lo a gerar seus memorandos e cartas. Agora, em vez de digitar dentro de campos em um arquivo de modelo de memo, tudo o que ele tem a fazer é digitar algumas linhas para produzir sua nota agradável e ameaçadora. A Listagem 4.1 mostra o que ele tem que digitar. Listagem 4.1. Usando o módulo Letter. 1 usrbinperl - w 2 3 Descomente a linha abaixo para incluir o diretório atual em Inc. 4 push (Inc, pwd) 5 6 use Letter 7 8 Letter :: To (quotMar Gambling Manquot, quotThe money for Lucky Dog, Race 2quot) 9 Letter :: ClaimMoneyNice () 10 Letter :: ThankDem () 11 Letter :: Finish () A declaração Letter de uso está presente para forçar o intérprete Perl a incluir o código do módulo no programa aplicativo. O módulo deve estar localizado no diretório usrlibperl5, ou você pode colocá-lo em qualquer diretório listado na matriz Inc. A matriz Inc é a lista de diretórios que o intérprete Perl procurará ao tentar carregar o código para o módulo nomeado. A linha comentada (número 4) mostra como adicionar o diretório de trabalho atual para incluir o caminho. As próximas quatro linhas no arquivo geram o assunto para a carta. É o resultado da utilização do módulo Letter: Para: Mr. Gambling Man Fm: Rudious Maximus, Loan Shark Dt: Qua 7 de fevereiro 10:35:51 CST 1996 Re: O dinheiro para Lucky Dog, Race 2 Chegou à minha atenção Que sua conta está muito atrasada. Você vai nos pagar em breve Ou quer que eu venha ova Obrigado pelo seu apoio. O arquivo do módulo de letras é mostrado na Listagem 4.2. O nome do pacote é declarado na primeira linha. Como essas funções de módulos serão exportadas, uso o módulo Exportador. Portanto, a declaração usa o Exportador para herdar a funcionalidade do módulo Exportador. Outra etapa necessária é colocar a palavra Exportada na matriz ISA para permitir a procura de Exportados. pm. A matriz ISA é uma matriz especial dentro de cada pacote. Cada item na matriz lista onde mais procurar um método se não puder ser encontrado no pacote atual. A ordem em que os pacotes estão listados na matriz ISA é a ordem em que Perl procura símbolos não resolvidos. Uma classe que está listada na matriz ISA é referida como a classe base dessa classe específica. Perl irá armazenar em cache os métodos que faltam encontrados nas classes base para futuras referências. A modificação da matriz ISA irá eliminar o cache e fazer com que Perl procure todos os métodos novamente. Vejamos agora o código para Letter. pm na Listagem 4.2. Listagem 4.2. O módulo Letter. pm. 1 pacote Carta 2 3 requer Exportador 4 ISA (Exportador) 5 6 cabeça1 NOME 7 8 Carta - Módulo de amostra para gerar cabeçalho para você 9 10 cabeça1 SINOPSE 11 12 uso Carta 13 14 Carta :: Data () 15 Carta :: Para (nome , Empresa, endereço) 16 17 Então, um dos seguintes: 18 Letter :: ClaimMoneyNice () 19 Letter :: ClaimMoney () 20 Letter :: ThreatBreakLeg () 21 22 Letter :: ThankDem () 23 Letter :: Finish () 24 25 head1 DESCRIÇÃO 26 27 Este módulo fornece um pequeno exemplo de geração de uma carta para um 28 tubarão de empréstimo de vizinhança amigável. 29 30 O código começa após a instrução quotcutquot. 31 corte 32 33 EXPORTAÇÃO qw (Data, 34 Para, 35 ReclamoMoney, 36 ReclamoMoneyNice, 37 ThankDem, 38 Conclusão) 39 40 41 Imprimir data de hoje 42 43 sub Letter :: Data 44 data data 45 imprimir quotn Hoje é data 46 47 48 sub Carta :: Para 49 local (nome) deslocamento 50 local (assunto) mudança 51 imprimir quotn Para: nomequot 52 imprimir quotn Fm: Rudious Maximus, empréstimo Sharkquot 53 imprimir quotn Dt: quot, date 54 imprimir quotn Re: subjectquot 55 imprimir quotnnquot 56 Imprimir quotnnquot 57 58 sub Letter :: ClaimMoney () 59 imprimir quotn Você me deve dinheiro. Obtenha seu ato togetherquot 60 print quotn Você quer que eu envie Bruno para quot 61 print quotn cole-o. Ou você vai pagar a subscrição 62 63 64 sub Letter :: ClaimMoneyNice () 65 imprimir quotn Chegou a minha atenção que sua conta é quot 66 imprimir quotn way over due. quot 67 imprimir quotn Você vai nos pagar em breve ... não 68 Imprimir quotn ou você gostaria que eu venha ovahquot 69 70 71 sub Letter :: ThreatBreakLeg () 72 imprimir quotn aparentemente cartas como estas não ajudam 73 imprimir quotn Eu vou ter que fazer um exemplo de youquot 74 imprimir quotn n Ver você no hospital , Palquot 75 76 77 sub Letter :: ThankDem () 78 imprimir quotnn Obrigado pelo seu suporte 79 80 81 sub Letter :: Finish () 82 printf quotnnnn Sincerelyquot 83 printf quotn Rudious n 84 84 86 86 1 Linhas que contêm o sinal de igualdade são usadas Para documentação. Você deve documentar cada módulo para sua própria referência. Os módulos Perl não precisam ser documentados, mas é uma boa idéia escrever algumas linhas sobre o que seu código faz. Daqui a poucos anos, você pode esquecer sobre o que é um módulo. Uma boa documentação é sempre uma obrigação se você quiser lembrar o que fez no passado. Eu cobrem os estilos de documentação usados ​​para o Perl no Capítulo 8. quotDocumenting Perl Scripts. quot Para este módulo de exemplo, a declaração head1 inicia a documentação. Tudo para a declaração de corte é ignorado pelo intérprete Perl. Em seguida, o módulo lista todas as funções exportadas por este módulo na matriz EXPORT. A matriz EXPORT define todos os nomes das funções que podem ser chamados pelo código externo. Se você não listar uma função nesta matriz EXPORT, não será visto por módulos de código externos. Seguir a matriz EXPORT é o corpo do código, uma sub-rotina de cada vez. Depois de todas as sub-rotinas serem definidas, a declaração final 1 encerra o arquivo do módulo. 1 deve ser a última linha executável no arquivo. Vejamos algumas das funções definidas neste módulo. A primeira função a observar é a função Data simples, as linhas 43 a 46, que imprime a data e a hora do UNIX atual. Não há parâmetros para esta função, e ele não retorna nada significativo de volta ao chamador. Observe o uso da minha antes da variável de data na linha 44. A minha palavra-chave é usada para limitar o escopo da variável dentro das chaves de curvatura das funções da Data. O código entre chaves é conhecido como um bloco. As variáveis ​​declaradas dentro de um bloco são limitadas no escopo dentro das chaves curly. Em 49 e 50, o nome e o assunto das variáveis ​​locais são visíveis para todas as funções. Você também pode declarar variáveis ​​com o qualificador local. O uso do local permite que uma variável esteja no escopo para o bloco atual, bem como para outros blocos de código chamados de dentro deste bloco. Assim, um x local declarado dentro de um bloco é visível para todos os blocos subseqüentes chamados de dentro deste bloco e podem ser referenciados. No código de exemplo a seguir, a variável de nome de funções ToTitled pode ser acessada, mas não os dados no iphone. 1 sub Letter :: ToTitled 2 local (name) shift 3 my (phone) shift O código de exemplo para Letter. pm mostrou como extrair um parâmetro por vez. A sub-rotina To () leva dois parâmetros para configurar o cabeçalho do memorando. O uso de funções dentro de um módulo não é diferente de usar e definir módulos Perl dentro do mesmo arquivo de código. Os parâmetros são passados ​​por referência, a menos que especificado de outra forma. As múltiplas matrizes passadas para uma sub-rotina, se não for explicitamente desreferenciada usando a barra invertida, são concatenadas. A matriz de entrada em uma função é sempre uma matriz de valores escalares. Passar valores por referência é a maneira preferida em Perl para passar uma grande quantidade de dados em uma sub-rotina. (Consulte o Capítulo 3. quotReferences. quot) Outro módulo de exemplo: Finanças O módulo Finanças, mostrado na Listagem 4.3, é usado para fornecer cálculos simples para valores de empréstimo. Usar o módulo Finanças é direto. Todas as funções são escritas com os mesmos parâmetros, conforme mostrado na fórmula para as funções. Vamos ver como o valor futuro de um investimento pode ser calculado. Por exemplo, se você investir alguns dólares, pv. Em uma ligação que oferece uma taxa de porcentagem fixa, r. Aplicado em intervalos conhecidos para n períodos de tempo, qual é o valor da ligação no momento da expiração. Neste caso, você estará usando a seguinte fórmula: fv pv (1r) n A função para obter o valor futuro é declarada como FutureValue . Consulte o Listado 4.3 para ver como usá-lo. Lista 4.3. Usando o módulo Finanças. 1 usrbinperl - w 2 3 push (Inc, pwd) 4 uso Finanças 5 6 empréstimo 5000.00 7 apr 3.5 APR 8 ano 10 em anos. 9 10 ------------------------------------------------ ---------------- 11 Calcule o valor no final do empréstimo se o interesse 12 for aplicado todos os anos. 13 ------------------------------------------------- --------------- 14 time-year 15 fv1 Finanças :: FutureValue (empréstimo, abril, hora) 16 imprimir quotn Se o interesse for aplicado no final do ano 17 imprimir quotn O valor futuro para um Empréstimo de quot. empréstimo. Quotnquot 18 imprime quot em um APR de quot, apr. Quot for quot, time, quot yearsquot 19 printf quot is 8.2f nquot. Fv1 20 21 ----------------------------------------------- ----------------- 22 Calcule o valor no final do empréstimo se o interesse 23 for aplicado todos os meses. 24 ------------------------------------------------- --------------- 25 taxa 12 de abril APR 26 horário 12 em meses 27 fv2 Finanças :: FutureValue (empréstimo, taxa e tempo) 28 29 imprimir quotn Se o interesse for aplicado no final de Cada mês 30 imprimir quotn O valor futuro para um empréstimo de quot. empréstimo. Quotnot 31 imprimir quot em um APR de quot, apr. Quot for quot, time, quot monthsquot 32 printf quot is 8.2f nquot. Fv2 33 34 printf quotn A diferença de valor é 8.2fquot, fv2 - fv1 35 printf quotn Portanto, ao aplicar o interesse em períodos de tempo mais curtos, 36 imprimir o quotn estamos realmente recebendo mais dinheiro em interesse. nquot Aqui está o exemplo de entrada e saída do Listado 4.3. Testme Se os juros forem aplicados no final do ano O valor futuro para um empréstimo de 5000 em um APR de 3,5 para 10 anos é de 7052.99 Se os juros forem aplicados no final de cada mês O valor futuro de um empréstimo de 5000 em um APR de 3,5 para 120 meses é 7091.72 A diferença de valor é 38.73 Portanto, ao aplicar o interesse em períodos de tempo mais curtos, estamos realmente recebendo mais dinheiro em interesse. A revelação na saída é o resultado da comparação de valores entre fv1 e fv2. O valor fv1 é calculado com a aplicação de interesse uma vez por ano durante a vida do vínculo. Fv2 é o valor se o interesse é aplicado a cada mês na taxa de juros mensal equivalente. O pacote Finance. pm é mostrado na Listagem 4.4 nas fases iniciais de desenvolvimento. Lista 4.4. O pacote Finance. pm. 1 pacote Finanças 2 3 requerem Exportador 4 ISA (Exportador) 5 6 head1 Finance. pm 7 8 Calculadora Financeira - Cálculos financeiros facilitados com Perl 9 10 cabeça 2 11 uso Finanças 12 13 pv 10000.0 14 15 taxa 12,5 12 TAEG por mês. 16 17 tempo 360 meses para empréstimo para amadurecer 18 19 fv FutureValue () 20 21 imprimir fv 22 23 cortar 24 25 EXPORTAR qw (FutureValue, 26 PresentValue, 27 FVofAnnuity, 28 AnnuityOfFV, 29 getLastAverage, 30 getMovingAverage, 31 SetInterest) 32 33 34 Globals, se houver 35 36 37 local defaultInterest 5.0 38 39 sub Finance :: SetInterest () 40 my rate shift () 41 defaultInterest rate 42 printf quotn defaultInterest ratequot 43 44 45 -------------- -------------------------------------------------- ---- 46 Notas: 47 1. A taxa de juros r é dada em um valor de 0-100. 48 2. O n dado nos termos é a taxa em que o interesse 49 é aplicado. 50 51 ------------------------------------------------ -------------------- 52 53 ---------------------------- ---------------------------------------- 54 Valor atual de um investimento dado 55 fv - Um valor futuro 56 r - taxa por período 57 n - número de período 58 ---------------------------------- ---------------------------------- 59 sub Finance :: FutureValue () 60 my (pv, r, n ) 61 my fv pv ((1 (r100)) n) 62 return fv 63 64 65 ------------------------------ -------------------------------------- 66 Valor presente de um investimento dado 67 fv - um futuro Valor 68 r - taxa por período 69 n - número de período 70 ------------------------------------ -------------------------------- 71 sub Finance :: PresentValue () 72 my pv 73 my (fv, r, N) 74 pv fv ((1 (r100)) n) 75 retorno pv 76 77 78 79 ----------------------------- --------------------------------------- 80 Obter o valor futuro de uma anuidade dada 81 mp - Pagamento mensal da anuidade 82 r - taxa por período 83 n - número o F período 84 ----------------------------------------------- --------------------- 85 86 sub FVofAnnuity () 87 my fv 88 my oneR 89 my (mp, r, n) 90 91 oneR (1 r) n 92 fv mp ((oneR - 1) r) 93 retorno fv 94 95 96 --------------------------------- ----------------------------------- 97 Obter a anuidade dos seguintes bits de informação 98 r - taxa por Período 99 n - número de período 100 fv - Valor futuro 101 ------------------------------------- ------------------------------- 102 103 sub AnnuityOfFV () 104 my mp mp - Pagamento mensal da anuidade 105 my oneR 106 My (fv, r, n) 107 108 oneR (1 r) n 109 mp fv (r (oneR-1)) 110 retorno mp 111 112 113 ----------------- -------------------------------------------------- - 114 Obter a média dos últimos valores quotnquot em uma matriz. 115 ------------------------------------------------- ------------------- 116 O último número de contagem de elementos da matriz em valores 117 O número total de elementos em valores está no número 118 119 sub getLastAverage () 120 my (Contagem, número, valores) 121 my i 122 123 my a 0 124 retorno 0 se (contagem 0) 125 para (i 0 ilt count i) 126 um número de valores - i - 1 127 128 retornar uma contagem 129 130 131 --- -------------------------------------------------- --------------- 132 Obter uma média móvel dos valores. 133 ------------------------------------------------- ------------------- 134 O tamanho da janela é o primeiro parâmetro, o número de itens na matriz passada 135 é o próximo. (Isso pode ser facilmente calculado dentro da função 136 usando a função scalar (), mas a sub-rotina mostrada aqui 137 também está sendo usada para ilustrar como passar ponteiros.) A referência à matriz 138 de valores é passada a seguir, seguida de um Referência ao lugar 139, os valores de retorno devem ser armazenados. 140 141 sub getMovingAve () 142 my (contagem, número, valores, motionAve) 143 meu i 144 meu a 0 145 meu v 0 146 147 retorno 0 se (contagem 0) 148 retorno -1 se (número de contagem gt) 149 retornar - 2 se (count lt 2) 150 151 moveAve0 0 152 movingAvenumber - 1 0 153 para (i0 iltcounti) 154 v valuesi 155 av count 156 movingAvei 0 157 158 para (icount iltnumberi) 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 a declaração da função FutureValue com (). Os sinais de três dólares juntos significam que três números escalares passaram para a função. Este escopo extra está presente para validar o tipo de parâmetros passados ​​para a função. Se você fosse passar uma string em vez de um número na função, você receberia uma mensagem muito semelhante a esta: Demasiados argumentos para Finanças :: FutureValue na. f4.pl linha 15, quase quottime) quot Execução de. f4.pl abortado devido a erros de compilação. O uso de protótipos ao definir funções impede o envio de valores diferentes do que a função espera. Use ou para passar em uma série de valores. Se você está passando por referência, use ou para mostrar uma referência escalar para uma matriz ou hash, respectivamente. Se você não usar a barra invertida, todos os outros tipos no protótipo da lista de argumentos serão ignorados. Outros tipos de desqualificadores incluem um e comercial para uma referência a uma função, um asterisco para qualquer tipo e um ponto e vírgula para indicar que todos os outros parâmetros são opcionais. Agora, olhe para a última declaração de função MovingAverage, que especifica dois números inteiros na frente seguido de uma matriz. A maneira como os argumentos são usados ​​na função é atribuir um valor a cada um dos dois escalares, contagem e número. Enquanto tudo o resto é enviado para a matriz. Olhe para a função getMovingAverage () para ver como dois arrays são passados ​​para obter a média móvel em uma lista de valores. A maneira de chamar a função getMovingAverage é mostrada na Listagem 4.5. Listagem 4.5. Usando a função de média móvel. 1 usrbinperl - w 2 3 push (Inc, pwd) 4 use Finance 5 6 valores (12,22,23,24,21,23,24,23,23,21,29,27,26,28) 7 mv ( 0) 8 tamanho escalar (valores) 9 imprimir quotn Valores para trabalhar com nquot 10 imprimir quot Número de valores tamanho nquot 11 12 ------------------------ ---------------------------------------- 13 Calcular a média da função acima 14 - -------------------------------------------------- ------------- 15 ave Finanças :: getLastAverage (5, tamanho, valores) 16 imprimir quotn Média dos últimos 5 dias ave nquot 17 18 Finanças :: getMovingAve (5, tamanho, valores, mv ) 19 imprimir quotn Média móvel com janela de 5 dias n nquot Heres o resultado da Lista 4.5: Valores para trabalhar com Número de valores 14 Média dos últimos 5 dias 26.2 A função getMovingAverage () leva dois escalares e duas referências a arrays como escalares. Dentro da função, os dois escalares para os arrays são desreferenciados para serem usados ​​como matrizes numéricas. O conjunto de valores retornado é inserido na área passada como segunda referência. Se os parâmetros de entrada não tivessem sido especificados para cada matriz referenciada, a referência da matriz movingAve teria sido vazia e teria causado erros no tempo de execução. Em outras palavras, a seguinte declaração não está correta: sub getMovingAve () O vomité resultante das mensagens de erro de um protótipo de função ruim é o seguinte: Uso do valor não inicializado na linha Finance. pm 128. Uso do valor não inicializado na linha Finance. pm 128. Uso do valor não inicializado na linha Finance. pm 128. Uso do valor não inicializado na linha Finance. pm 128. Uso do valor não inicializado na linha Finance. pm 128. Uso do valor não inicializado na linha Finance. pm 133. Uso do valor não inicializado Na linha Finance. pm 135. Uso do valor não inicializado na linha Finance. pm 133. Uso do valor não inicializado na linha Finance. pm 135. Uso do valor não inicializado na linha Finance. pm 133. Uso do valor não inicializado na linha Finance. pm 135 Uso do valor não inicializado na linha Finance. pm 133. Uso do valor não inicializado na linha Finance. pm 135. Uso do valor não inicializado na linha Finance. pm 133. Uso do valor não inicializado na linha 135 Finance. pm. Uso do valor não inicializado em Linha Finance. pm 133. Uso de valor não inicializado e 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.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 andor acceptance tests. Remember, programmers are lazy and impatient, and they don39t like being held back by their programming environment. When you test only what might break, your unit test suite will remain a lightweight and effective development tool. Please note that if you and your partner are new to test-driven design, it39s probably better to err on the side of caution and to test too much. With experience, you39ll learn which tests are redundant and which are especially helpful. There are no magic formulas here. Testing is an art that takes time to master. Satisfy The Test, Don39t Trick It Returning to our example, the implementation of new that satisfies this case is: This is the minimal code which satisfies the above test. length doesn39t need to be stored, and we don39t need to compute alpha. We39ll get to them when we need to. But wait, you say, wouldn39t the following code satisfy the test, too Yes, you can trick any test. However, it39s nice to treat programmers like grown-ups (even though we don39t always act that way). No one is going to watch over your shoulder to make sure you aren39t cheating your own test. The first implementation of new is the right amount of code, and the test is sufficient to help guide that implementation. The design calls for an object to hold state, and an object creation is what needed to be coded. Test Base Cases First What we39ve tested thus far are the base cases . that is, tests that validate the basic assumptions of the API. When we test basic assumptions first, we work our way towards the full complexity of the complete implementation, and it also makes the test more readable. Test-first design works best when the implementation grows along with the test cases. There are two base cases for the compute function. The first base case is that the initial value of the average is just the number itself. There39s also the case of inputting a value equal to the average, which should leave the average unchanged. These cases are coded as follows: The is function from Test::More lets us compare scalar values. Note the change to the instantiation test case that allows us to use the instance ( ema ) for subsequent cases. Reusing results of previous tests shortens the test, and makes it easier to understand. The implementation that satisfies these cases is: The initialization of alpha was added to new . because compute needs the value. new initializes the state of the object, and compute implements the EMA algorithm. self-gt is initially undef so that case can be detected. Even though the implementation looks finished, we aren39t done testing. The above code might be defective. Both compute test cases use the same value, and the test would pass even if, for example, self-gt and value were accidentally switched. We also need to test that the average changes when given different values. The test as it stands is too static, and it doesn39t serve as a good example of how an EMA works. Choose Self-Evident Data In a test-driven environment, programmers use the tests to learn how the API works. You may hear that XPers don39t like documentation. That39s not quite true. What we prefer is self-validating documentation in the form of tests. We take care to write tests that are readable and demonstrate how to use the API. One way to create readable tests is to pick good test data. However, we have a little bootstrapping problem: To pick good test data, we need valid values from the results of an EMA computation, but we need an EMA implementation to give us those values. One solution is to calculate the EMA values by hand. Or, we could use another EMA implementation to come up with the values. While either of these choices would work, a programmer reading the test cases would have to trust them or to recompute them to verify they are correct. Not to mention that we39d have to get the precision exactly right for our target platform. Use The Algorithm, Luke A better alternative is to work backwards through the algorithm to figure out some self-evident test data.5 To accomplish this, we treat the EMA algorithm as two equations by fixing some values. Our goal is to have integer values for the results so we avoid floating point precision issues. In addition, integer values make it easier for the programmer to follow what is going on. When we look at the equations, we see alpha is the most constrained value: today39s average today39s price x alpha yesterday39s average x (1 - alpha) alpha 2 (length 1) Therefore it makes sense to try and figure out a value of alpha that can produce integer results given integer prices. Starting with length 1, the values of alpha decrease as follows: 1, 23, 12, 25, 13, 27, and 14. The values 1, 12, and 25 are good candidates, because they can be represented exactly in binary floating point. 1 is a degenerate case, the average of a single value is always itself. 12 is not ideal, because alpha and 1 - alpha are identical, which creates a symmetry in the first equation: today39s average today39s price x 0.5 yesterday39s average x 0.5 We want asymmetric weights so that defects, such as swapping today39s price and yesterday39s average, will be detected. A length of 4 yields an alpha of 25 (0.4), and makes the equation asymmetric: today39s average today39s price x 0.4 yesterday39s average x 0.6 With alpha fixed at 0.4, we can pick prices that make today39s average an integer. Specifically, multiples of 5 work nicely. I like prices to go up, so I chose 10 for today39s price and 5 for yesterday39s average. (the initial price). This makes today39s average equal to 7, and our test becomes: Again, I revised the base cases to keep the test short. Any value in the base cases will work so we might as well save testing time through reuse. Our test and implementation are essentially complete. All paths through the code are tested, and EMA could be used in production if it is used properly. That is, EMA is complete if all we care about is conformant behavior. The implementation currently ignores what happens when new is given an invalid value for length . Although EMA is a small part of the application, it can have a great impact on quality. For example, if new is passed a length of -1, Perl throws a divide-by-zero exception when alpha is computed. For other invalid values for length . such as -2, new silently accepts the errant value, and compute faithfully produces non-sensical values (negative averages for positive prices). We can39t simply ignore these cases. We need to make a decision about what to do when length is invalid. One approach would be to assume garbage-in garbage-out. If a caller supplies -2 for length . it39s the caller39s problem. Yet this isn39t what Perl39s divide function does, and it isn39t what happens, say, when you try to de-reference a scalar which is not a reference. The Perl interpreter calls die . and I39ve already mentioned in the Coding Style chapter that I prefer failing fast rather than waiting until the program can do some real damage. In our example, the customer39s web site would display an invalid moving average, and one her customers might make an incorrect investment decision based on this information. That would be bad. It is better for the web site to return a server error page than to display misleading and incorrect information. Nobody likes program crashes or server errors. Yet calling die is an efficient way to communicate semantic limits (couplings) within the application. The UI programmer, in our example, may not know that an EMA39s length must be a positive integer. He39ll find out when the application dies. He can then change the design of his code and the EMA class to make this limit visible to the end user. Fail fast is an important feedback mechanism. If we encounter an unexpected die . it tells us the application design needs to be improved. Deviance Testing In order to test for an API that fails fast, we need to be able to catch calls to die and then call ok to validate the call did indeed end in an exception. The function diesok in the module Test::Exception does this for us. Since this is our last group of test cases in this chapter, here39s the entire unit test with the changeds for the new deviance cases highlighted: There are now 9 cases in the unit test. The first deviance case validates that length can39t be negative. We already know -1 will die with a divide-by-zero exception so -2 is a better choice. The zero case checks the boundary condition. The first valid length is 1. Lengths must be integers, and 2.5 or any other floating point number is not allowed. length has no explicit upper limit. Perl automatically converts integers to floating point numbers if they are too large. The test already checks that floating point numbers are not allowed so no explicit upper limit check is required. The implementation that satisfies this test follows: The only change is the addition of a call to die with an unless clause. This simple fail fast clause doesn39t complicate the code or slow down the API, and yet it prevents subtle errors by converting an assumption into an assertion. Only Test The New API One of the most difficult parts of testing is to know when to stop. Once you have been test-infected, you may want to keep on adding cases to be sure that the API is perfect. For example, a interesting test case would be to pass a NaN (Not a Number) to compute . but that39s not a test of EMA . The floating point implementation of Perl behaves in a particular way with respect to NaNs6. and Bivio::Math::EMA will conform to that behavior. Testing that NaNs are handled properly is a job for the Perl interpreter39s test suite. Every API relies on a tremendous amount of existing code. There isn39t enough time to test all the existing APIs and your new API as well. Just as an API should separate concerns so must a test. When testing a new API, your concern should be that API and no others. Solid Foundation In XP, we do the simplest thing that could possibly work so we can deliver business value as quickly as possible. Even as we write the test and implementation, we39re sure the code will change. When we encounter a new customer requirement, we refactor the code, if need be, to facilitate the additional function. This iterative process is called continuous design . which is the subject of the next chapter. It39s like renovating your house whenever your needs change. 7 A system or house needs a solid foundation in order to support continuous renovation. Unit tests are the foundation of an XP project. When designing continuously, we make sure the house doesn39t fall down by running unit tests to validate all the assumptions about an implementation. We also grow the foundation before adding new functions. Our test suite gives us the confidence to embrace change. Quality Software Management: Vol. 1 Systems Thinking . Gerald Weinberg, Dorset House, 1991, p. 236. Part of the Test-Simple distribution, available at search. cpan. orgsearchqueryTest-Simple I used version 0.47 for this book. Just a friendly reminder to program in pairs, especially when trying something new. Thanks to Ion Yadigaroglu for teaching me this technique. In some implementations, use of NaNs will cause a run-time error. In others, they will cause all subsequent results to be a NaN. Don39t let the thought of continuous house renovation scare you off. Programmers are much quieter and less messy than construction workers. Perl - Subroutines A Perl subroutine or function is a group of statements that together performs a task. You can divide up your code into separate subroutines. How you divide up your code among different subroutines is up to you, but logically the division usually is so each function performs a specific task. Perl uses the terms subroutine, method and function interchangeably. Define and Call a Subroutine The general form of a subroutine definition in Perl programming language is as follows minus The typical way of calling that Perl subroutine is as follows minus In versions of Perl before 5.0, the syntax for calling subroutines was slightly different as shown below. This still works in the newest versions of Perl, but it is not recommended since it bypasses the subroutine prototypes. Lets have a look into the following example, which defines a simple function and then call it. Because Perl compiles your program before executing it, it doesnt matter where you declare your subroutine. When above program is executed, it produces the following result minus Passing Arguments to a Subroutine You can pass various arguments to a subroutine like you do in any other programming language and they can be acessed inside the function using the special array . Thus the first argument to the function is in 0, the second is in 1, and so on. You can pass arrays and hashes as arguments like any scalar but passing more than one array or hash normally causes them to lose their separate identities. So we will use references ( explained in the next chapter ) to pass any array or hash. Lets try the following example, which takes a list of numbers and then prints their average minus When above program is executed, it produces the following result minus Passing Lists to Subroutines Because the variable is an array, it can be used to supply lists to a subroutine. However, because of the way in which Perl accepts and parses lists and arrays, it can be difficult to extract the individual elements from . If you have to pass a list along with other scalar arguments, then make list as the last argument as shown below minus When above program is executed, it produces the following result minus Passing Hashes to Subroutines When you supply a hash to a subroutine or operator that accepts a list, then hash is automatically translated into a list of keyvalue pairs. For example minus When above program is executed, it produces the following result minus Returning Value from a Subroutine You can return a value from subroutine like you do in any other programming language. If you are not returning a value from a subroutine then whatever calculation is last performed in a subroutine is automatically also the return value. You can return arrays and hashes from the subroutine like any scalar but returning more than one array or hash normally causes them to lose their separate identities. So we will use references ( explained in the next chapter ) to return any array or hash from a function. Lets try the following example, which takes a list of numbers and then returns their average minus When above program is executed, it produces the following result minus Private Variables in a Subroutine By default, all variables in Perl are global variables, which means they can be accessed from anywhere in the program. But you can create private variables called lexical variables at any time with the my operator. The my operator confines a variable to a particular region of code in which it can be used and accessed. Outside that region, this variable cannot be used or accessed. This region is called its scope. A lexical scope is usually a block of code with a set of braces around it, such as those defining the body of the subroutine or those marking the code blocks of if, while, for, foreach, and eval statements. Following is an example showing you how to define a single or multiple private variables using my operator minus Lets check the following example to distinguish between global and private variables minus When above program is executed, it produces the following result minus Temporary Values via local() The local is mostly used when the current value of a variable must be visible to called subroutines. A local just gives temporary values to global (meaning package) variables. This is known as dynamic scoping . Lexical scoping is done with my, which works more like Cs auto declarations. If more than one variable or expression is given to local, they must be placed in parentheses. This operator works by saving the current values of those variables in its argument list on a hidden stack and restoring them upon exiting the block, subroutine, or eval. Lets check the following example to distinguish between global and local variables minus When above program is executed, it produces the following result minus State Variables via state() There are another type of lexical variables, which are similar to private variables but they maintain their state and they do not get reinitialized upon multiple calls of the subroutines. These variables are defined using the state operator and available starting from Perl 5.9.4. Lets check the following example to demonstrate the use of state variables minus When above program is executed, it produces the following result minus Prior to Perl 5.10, you would have to write it like this minus Subroutine Call Context The context of a subroutine or statement is defined as the type of return value that is expected. This allows you to use a single function that returns different values based on what the user is expecting to receive. For example, the following localtime() returns a string when it is called in scalar context, but it returns a list when it is called in list context. In this example, the value of timestr is now a string made up of the current date and time, for example, Thu Nov 30 15:21:33 2000. Conversely minus Now the individual variables contain the corresponding values returned by localtime() subroutine.

No comments:

Post a Comment