Mostrando entradas con la etiqueta Perl. Mostrar todas las entradas
Mostrando entradas con la etiqueta Perl. Mostrar todas las entradas

lunes, 21 de septiembre de 2015

Perl: Pairing in Pair programming without repeated

Script para formar parejas sin repetición de pares para pairing


#!/usr/bin/perl -s
# Perl Scrip to Pairing in Pair programming
# Example:

# La primera vez llamar con argumentos:
# perl pairing.pl "Dario" "Gaby" "Claudio" "Frula" "Ricardo" "Raul" "Esteban" "Adrian" 

# A partir de la segunda vez llamar sin argumentos porque los nombres fueron guardados en un archivo.
# perl pairing.pl
   
use strict;
use warnings;


# Begin main

# @ARGV is a array of command line arguments
if (scalar @ARGV == 0){
    # File input. Read from file
    my @input_argv = @{read_array_from_file('file_example.txt')};
    do_pairing_no_repeated(\@input_argv);
    }elsif (scalar @ARGV > 3){
        #ARG input. Read from arguments of command line
        do_pairing_repeated(\@ARGV);
        }else{
            print "Arguments must be more than 3! \n";
        }

# End main

# Run pairing with repeated
sub do_pairing_repeated{
    my ($ARGV) = @_; #array reference
   
    my @pairing_list=();
    do_pairing($ARGV, \@pairing_list);
    print_pairing(\@pairing_list);
    save('file_example.txt', \@pairing_list);
}

# Run pairing NO repeated
sub do_pairing_no_repeated{
    my ($ARGV) = @_; #array reference
    my $no_repeated=1;
    my @pairing_list;
    do{
        @pairing_list=();
        do_pairing($ARGV, \@pairing_list);
        $no_repeated = compare_if_no_repeated($ARGV, \@pairing_list);
    } until($no_repeated);
    print_pairing(\@pairing_list);
    save('file_example.txt', \@pairing_list);
}

# Checks if couples are repeated in the two arrays
sub compare_if_no_repeated{
    my ($origin_list, $pairing_list) = @_; #array reference
   
    for(my $i=0; $i<=scalar @{$origin_list} - 1; $i = $i + 2){
       
        if ($i < scalar @{$origin_list} - 1) {
            if (are_repeated(@{$origin_list}[$i], @{$origin_list}[$i + 1], @{$pairing_list}[$i], @{$pairing_list}[$i + 1])){
                return 0;
                }
           
            }
    }    
    return 1;
}

# Checks if the two pairs are the same (repeated pairs)
sub are_repeated{
    my ($pair_1_a, $pair_1_b, $pair_2_a, $pair_2_b) = @_;
   
    if (($pair_1_a eq $pair_2_a) && ($pair_1_b eq $pair_2_b)){
        return 1
        }
    if (($pair_1_a eq $pair_2_b) && ($pair_1_b eq $pair_2_a)){
        return 1
        }
    return 0;
}

# Print pairing names from a members array
sub print_pairing{
    my ($members) = @_; #array reference
   
    for(my $index=0; $index<=scalar @{$members} - 1; $index = $index + 2){
        print @{$members}[$index] . "-";
        if ($index < scalar @{$members} - 1) {
            print @{$members}[$index + 1] . "\n";
            }else{
                print "none \n";
                }
    }    
}

# Run pairing
sub do_pairing{
    my ($members, $pairing_list) = @_; #array reference

    my @members_copy;
   
    foreach my $elem (@{$members}) {
        push (@members_copy, $elem);
    }
   
    my $members_count = scalar @members_copy;
    do{
        my $selected =  get_member_and_remove_it_random(\@members_copy);
        $members_count = $members_count - 1;
        push (@{$pairing_list}, $selected);
       
    } until($members_count==0);
}

# Retrieves a member and removes it from the array.
sub get_member_and_remove_it_random{
    my ($members) = @_; #array reference
    my $size = scalar @{$members};
    my $random_number = int(rand($size));
    my $removed_member =  splice @{$members}, $random_number, 1;
    return $removed_member;
}

sub read_array_from_file{
    my ($filename) = @_;
    my @input_array = ();

    if (open(my $fh, '<:encoding(UTF-8)', $filename)) {
        while (my $row = <$fh>) {
            chomp $row;
            push (@input_array, $row);
        }
    } else {
        warn "Could not open file '$filename' $!";
        }
    return \@input_array;
}

sub save{
    my ($filename, $array_reference) = @_;
   
    open(my $fh, '>:encoding(UTF-8)', $filename) or die "Could not open file '$filename' $!";
   
    foreach my $elem (@{$array_reference}) {
        print $fh "$elem\n";
    }

    close $fh;
}

miércoles, 9 de septiembre de 2015

Perl: Pairing in Pair programming

Script para formar parejas para programación de a pares


#!/usr/bin/perl -s
# File: pairing.pl 
# Perl Scrip to Pairing in Pair programming
# Command line example:
# perl pairing.pl "Dario" "Karina" "Claudia" "Pancho"

  
use strict;
use warnings;

# Begin main
# @ARGV is a array of command line arguments
if (scalar @ARGV > 0){
    runPairing(\@ARGV);
}else{
    print "No arguments. Enter names. For example: \n";
    print "perl pairing.pl \"name1\" \"name2\" \"name3\" \"name4\" \n";
    }

# End main


# Run pairing
sub runPairing{
    my ($members) = @_; #array reference
    my $members_count = scalar @{$members};
    my $pair_count = 1;
    do{
        my $first_selected =  getMemberAndRemoveItRandom($members);
        $members_count = $members_count - 1;
        if ($members_count > 0){
            my $second_selected =  getMemberAndRemoveItRandom($members);
            $members_count = $members_count - 1;
            print "Pair $pair_count: " . $first_selected;
            print " - " . $second_selected . " \n";
            }else{
                print "Pair $pair_count: " . $first_selected . " - none\n";
                }
        $pair_count = $pair_count + 1;
    } until($members_count==0);
}

# Retrieves a member and removes it from the array.
sub getMemberAndRemoveItRandom{
    my ($members) = @_; #array reference
    my $size = scalar @{$members};
    my $random_number = int(rand($size));
    my $removed_member =  splice @{$members}, $random_number, 1;
    return $removed_member;
}



martes, 24 de febrero de 2015

Perl: Constants

Constantes en Perl y Moose


Ejemplo de como usar constantes en Perl usando Moose


{
    package Parent;
    use Moose;
    use namespace::autoclean;

    use constant MY_CONSTANT => 'CONSTANT';

    use constant {
        MY_CONSTANT => 'CONSTANT'
        NO_LEVEL => 0,
        MY_LEVEL => 1,
    };

    sub printMyConstant {
        my $self = shift;
        print &MY_CONSTANT;
    }


    __PACKAGE__->meta->make_immutable;
};

{
    package Child;
    use Moose;
    use namespace::autoclean;

    extends 'Parent';

    sub printMyLevel {
        my $self = shift;
        my $class = ref $self;

        print $class->MY_LEVEL;
        print &Parent::MY_CONSTANT;
    }
    __PACKAGE__->meta->make_immutable;
}

package main;

my $child = Child->new;
$child->printMyLevel;



miércoles, 18 de febrero de 2015

Perl: Using Maybe attribute not die on undef

Perl: Moose, Using Maybe attribute not die on undef


Problema


Cuando definimos atributos en Moose con constraint en tiempo de ejecución podemos encontrarnos con el siguiente tipo de excepciones: "Attribute (AttributeName) does not pass the type constraint because: Validation failed for 'Str' with value undef"
Para evitarlo podemos usar "Maybe". A continuación un ejemplo:

Class to Test


package ClassWithMaybe;

use Moose;

has 'atributoSinConstraints' => ( 
                is => 'rw', 
                isa => 'Maybe[Str]', 
                default => '',
                reader => 'getAtributoSinConstraints',
                writer => 'setAtributoSinConstraints'
                ); # will NOT die on undef

has 'atributoConConstraints' => (
                is => 'rw', 
                isa => 'Str',
                reader => 'getAtributoConConstraints',
                writer => 'setAtributoConConstraints'
                ); # will die on undef (esto puede generar la exception mostrada anteriormente)
    
sub BUILD {
    my $self = shift;
    $self->setAtributoSinConstraints('') unless defined $self->getAtributoSinConstraints;
}

no Moose; __PACKAGE__->meta->make_immutable;

TEST


package ClassWithMaybeTest;

use Moose;
use Test::More;
use Test::Exception; #cpanm Test::Exception
use ClassWithMaybe;

throws_ok { ClassWithMaybe->new( atributoConConstraints => undef ) }
    qr/Validation failed for 'Str' with value undef/; # will die on undef
    
lives_ok  { ClassWithMaybe->new( atributoConConstraints => "with data" ) } 
    'atributoConConstraints with data ok';

lives_ok  { ClassWithMaybe->new( atributoSinConstraints => undef ) } 
    'atributoSinConstraints supplied as undef'; # will not die on undef

my $classWithMaybe = ClassWithMaybe->new( atributoSinConstraints => undef , atributoConConstraints => "with data");

is $classWithMaybe->getAtributoSinConstraints, '', "atributoSinConstraints is ''";

$classWithMaybe = ClassWithMaybe->new();
$classWithMaybe->setAtributoSinConstraints(undef);# will not die on undef

is $classWithMaybe->getAtributoSinConstraints, undef, "atributoSinConstraints is undef";

done_testing;

Run test


perl ClassWithMaybeTest.t
ok 1 - threw Regexp ((?^:Validation failed for 'Str' with value undef))
ok 2 - atributoConConstraints with data ok
ok 3 - atributoSinConstraints supplied as undef
ok 4 - atributoSinConstraints is ''
ok 5 - atributoSinConstraints is undef
1..5


References:




jueves, 12 de febrero de 2015

Perl: How to Debug in Perl

How to Debug in Perl?

Perl Debugger

Si ejecutamos perl con la opción -d se ejecuta en modo debugger.


Código para hacer debug:

#!/usr/bin/perl
# example.pl
my $name = "Daro";
my $email = "daro@daro.com.ar";
$DB::single = 1; #breakpoint
if (!defined($email)){
print "Mail es undef. \n";
}else{
print "Mail es defined. \n";
}
$DB::single = 1; #breakpoint
if (!defined($name)){
print "Name es undef. \n";
}else{
print "Name es defined. \n";
}
#end script example.pl

Ejecutar por consola:

perl -d example.pl 

Loading DB routines from perl5db.pl version 1.33
Editor support available.

Enter h or `h h' for help, or `man perldebug' for more help.

main::(ej.pl:5): my $name = "Daro";
  DB<1> c
main::(ej.pl:8): if (!defined($email)){
  DB<1> c
Mail es defined. 
main::(ej.pl:14): if (!defined($name)){
  DB<1> c
Name es defined. 
Debugged program terminated.  Use q to quit or R to restart,
  use o inhibit_exit to avoid stopping after program termination,
  h q, h R or h o to get additional info.  

  DB<1> h
List/search source lines:               Control script execution:
  l [ln|sub]  List source code            T           Stack trace
  - or .      List previous/current line  s [expr]    Single step [in expr]
  v [line]    View around line            n [expr]    Next, steps over subs
  f filename  View source in file         <CR/Enter>  Repeat last n or s
  /pattern/ ?patt?   Search forw/backw    r           Return from subroutine
  M           Show module versions        c [ln|sub]  Continue until position
Debugger controls:                        L           List break/watch/actions
  o [...]     Set debugger options        t [expr]    Toggle trace [trace expr]
  <[<]|{[{]|>[>] [cmd] Do pre/post-prompt b [ln|event|sub] [cnd] Set breakpoint
  ! [N|pat]   Redo a previous command     B ln|*      Delete a/all breakpoints
  H [-num]    Display last num commands   a [ln] cmd  Do cmd before line
  = [a val]   Define/list an alias        A ln|*      Delete a/all actions
  h [db_cmd]  Get help on command         w expr      Add a watch expression
  h h         Complete help page          W expr|*    Delete a/all watch exprs
  |[|]db_cmd  Send output to pager        ![!] syscmd Run cmd in a subprocess
  q or ^D     Quit                        R           Attempt a restart
Data Examination:     expr     Execute perl code, also see: s,n,t expr
  x|m expr       Evals expr in list context, dumps the result or lists methods.
  p expr         Print expression (uses script's current package).
  S [[!]pat]     List subroutine names [not] matching pattern
  V [Pk [Vars]]  List Variables in Package.  Vars can be ~pattern or !pattern.
  X [Vars]       Same as "V current_package [Vars]".  i class inheritance tree.
  y [n [Vars]]   List lexicals in higher scope <n>.  Vars same as V.
  e     Display thread id     E Display all thread ids.
For more help, type h cmd_letter, or run man perldebug for all docs.
  
DB<1> q




References:
http://perldoc.perl.org/perldebug.html

lunes, 6 de octubre de 2014

Perl: Unit Test con Test::More

Unit Test con Test::More y Test::MockObject


El módulo Test::More es un módulo para hacer unit test en Perl y Test::MockObject es un módulo que permite hacer mocking en forma fácil.


Ejemplo de un simple UnitTest

A continuación un simple ejemplo de un unit test con Test::More (usando la estructura de clase de Moose).

Clase a probar:


#File: Person.pm
package Person;

    use Moose;
    use strict; 
    use warnings; 
    use namespace::autoclean;
   
    has '_firstName' => (
                is         => 'rw', 
                isa        => 'Str', 
                required => 1,
                reader => 'getFirstName',
                writer => 'setFirstName',
    );    

    has '_secondName' => (
                is         => 'rw',
                isa        => 'Str', 
                required => 1,
                reader => 'getSecondName', 
                writer => 'setSecondName',
    );
    
sub getFullName{
  my ( $self ) = @_;
  my $full_name = join ' ' => $self->getFirstName(), $self->getSecondName();
  return $full_name;
}

no Moose;
__PACKAGE__->meta->make_immutable;
1;

Unit Test:


#File: PersonTest.t
package PersonTest;

    use Moose;
    use Test::More tests => 3; #Cantidad de test
    use Test::MockObject; #uso de mocking
    use strict; 
    use warnings; 
    use namespace::autoclean; 
    use Person; #Clase a probar
    
    #Primer test
    subtest 'classTest' => sub {
      plan tests => 2; #Cantidad de evaluaciones (aserciones) de test
      require_ok( 'Person' ); #Comprueba que esté el módulo
      my $persona = Person->new(_firstName=>"", _secondName=>"",);
      isa_ok ($persona, 'Person'); #Comprueba si es la clase correcta   
    };
    
    #Segundo test
    subtest 'getFullName' => sub {
      plan tests => 3; #Cantidad de evaluaciones (aserciones) de test
      my $persona = Person->new(_firstName=>"Diego", _secondName=>"Maradona",);
      is($persona->getFullName(),"Diego Maradona",'Full name is right');
      isnt ($persona->getFullName(), "Other name", "Bad full name!");
      ok( length $persona->getFirstName() == 5,       'First Name length is ok!'  );
    };  

    #Tercer test
    subtest 'getFullName_Using_Mock' => sub {
      plan tests => 1;
        my $mockPerson = Test::MockObject->new();
        $mockPerson->mock( 'getFullName',
             sub { 'Ejemplo' } ); #Mocking de la clase Person
      is( $mockPerson->getFullName,"Ejenplo",'Full name is ok with mocking');
  };

no Moose;
__PACKAGE__->meta->make_immutable;
1;


Resultado de la corrida del test:


1..3
    1..2
    ok 1 - require Person;
    ok 2 - The object isa Person
ok 1 - classTest
    1..3
    ok 1 - Full name is right
    ok 2 - Bad full name!
    ok 3 - First Name length is ok!
ok 2 - getFullName
    1..1
    ok 1 - Full name is ok with mocking
ok 3 - getFullName_Using_Mock



Referencias:
-Test::More doc.
-Test::More wikipedia.
-Test::More Tutorial.
-Test::MockObject doc.

sábado, 4 de octubre de 2014

Perl: Switch Statement

Sentencia Switch

Las versiones antiguas de Perl (la vieja escuela o "perl old school") no tienen sentencia switch. O sea que la sentencia switch no es propia del lenguaje, pero se puede simular o hacer construcciones que cumplan el mismo propósito.
A continuación algunos ejemplos:

Ejemplo usando diferentes maneras de switch

#This is perl 5, version 14, subversion 2 (v5.14.2)
#File: UingSwitch.pm
package UsingSwitch;

    use Moose;
    use strict;
    use warnings;
    #use namespace::autoclean;
    use Switch; #Usado en switch_modo_1_

#Switch using 'use Switch' (usando el módulo Switch)
sub switch_modo_1_(){
  my ($self, $i) = @_;
  #use Switch
  switch ($i) {
case 0  { return 'uno' }
        case 2  { return 'dos' }
        case 3  { return 'tres' }
        case [4..9]  { return 'entre 4 y 9' }
        else {return 'Default...'}
        }
     
  return;
}

(Nota: Ojo... Que usar la librería Switch de Perl, impacta negativamente en el rendimiento aumentando el tiempo de ejecución. Si es importante el rendimiento puede ser preferible no usar la librería Switch.)

#Switch using bare block (usando estructura de bloques)
sub switch_modo_2_(){
  my ($self, $i) = @_;
  SWITCH: {
     $i == 1 && do { return "1";};
     $i == 2 && do { return "2";};
     $i == 3 && do { return "3";};
     return "Default...";
  }
=pod
  #Otra forma:
  $var = 2;
  SWITCH: {
    $var == 1 && do { print "1\n"; last SWITCH; };
    $var == 2 && do { print "2\n"; last SWITCH; };
    $var == 3 && do { print "3\n"; last SWITCH; };
    print "\$var is not equal with 1 or 2 or 3\n";
}
=cut
  return;
}

#Switch using hash (usando los valores de un hash)
sub switch_modo_3_(){
  my ($self, $i) = @_;
  my %my_switch = (
     1 => "1",
     2 => "2",
     3 => "3",
  );
  return $my_switch{$i};
}

#Switch using hash with functions (usando un hash con valores funciones)
sub switch_modo_4_(){
  my ($self, $i) = @_;
  my %my_switch = (
     1 => sub {return "uno";},
     2 => sub {return "dos";},
     3 => sub {return "tres";}
  );
  my $res = $my_switch{$i}->();
  return $res;
}

no Moose;
__PACKAGE__->meta->make_immutable; #no voy a cambiar mi clase
1;

#...............................................................................................
#test_UsingSwitch
#!/usr/bin/perl
#use strict;
use warnings;

use UsingSwitch;

my $ex = UsingSwitch->new();

#Switch using 'use Switch'
print $ex->switch_modo_1_(2); #imprime 'dos'
#Switch using bare block
print $ex->switch_modo_2_(1000); #Default
#Switch using hash
print $ex->switch_modo_3_(3); #Default
#Switch using hash with functions
print $ex->switch_modo_4_(1); #Default
print "...end \n";
#............................................................................................end

dario:~/examples$ perl test_UingSwitch.pl 
Esto imprime:
dosDefault...3uno...end 


Referencia:
-http://perldoc.perl.org/5.8.8/Switch.html.
-Writing a Switch Statement.
-Perl Switch statement.
-Older versions of Perl have no switch statement. How do I avoid a long if-else-if pattern?



Perl: POO con Moose, paso de parámetros

En perl todos los objetos son una referencia. Es decir, cuando tenes un $obj es una variable scalar que simplemente mantiene la referencia al objeto.

Ejemplo de paso de objetos

#This is perl 5, version 14, subversion 2 (v5.14.2)
#File: Example.pm
package Example;

    use Moose;
    use strict;
    use warnings;
    #use namespace::autoclean;

    has 'c' => (
                is         => 'rw', #Lectura-Escritura
                isa        => 'Maybe[Str]', #Tipo String
                reader => 'getValor', #getter
                writer => 'setValor', #setter
    );  

sub metodo1{
  my ($self) = @_;

  my $obj = Example->new(obj=>"Primer valor.");
  #$obj = $self->metodo2($obj);
  $self->metodo2($obj);
  print $obj->getValor() . "\n";#Modificado
  return;
}

sub metodo2{
  my ($self, $obj) = @_;

  $obj->setValor("Modificado..."); #usa el objeto pasado como argumento
  return $obj;
}

no Moose;
__PACKAGE__->meta->make_immutable; #no voy a cambiar mi clase
1;

#test_example.pl
#Main.......................................................................
#!/usr/bin/perl
#use strict;
use warnings;

use Example;

my $ex = Example->new();
print $ex->metodo1();
print "\n";
#...........................................................................end

Resultado:
~/examples$ perl test_example.pl
Modificado...


miércoles, 1 de octubre de 2014

Perl: HTML y UTF8 encoding

HTML y UTF8 encoding

Ejemplo de utf8 encoding:

#This is perl 5, version 14, subversion 2 (v5.14.2)
#File: ExampleEncoder.pm
package ExampleEncoder;

    use Moose;
    use strict;
    use warnings;
    #use namespace::autoclean;
    use HTML::Entities;
    use Encode::Encoder;
 
sub encodeHTMLtoUTF8{
  my ($self, $parametro) = @_;

  my $s = HTML::Entities::decode($parametro);
  $s = Encode::Encoder::encoder($s)->utf8;

  return $s;
}

no Moose;
__PACKAGE__->meta->make_immutable; #no voy a cambiar mi clase
1;

#!/usr/bin/perl
#use strict;
use warnings;
use ExampleEncoder;

my $ex = Example->new();
my $str = "C&oacute;rdoba";
print $ex->encodeHTMLtoUTF8($str);



domingo, 28 de septiembre de 2014

Perl: POO con Moose, Herencia

Herencia con Moose

Uso de herencia en Programación Orientada a Objetos con Perl Moose (perl 5).


1) Herencia simple (INHERITANCE)

#This is perl 5, version 14, subversion 2 (v5.14.2)
#File: Person.pm
package Person; #Super-Class: Es la super-clase

    use Moose;
    use strict; #Obliga a la programación segura y definición de variables
    use warnings; #Ayudará a encontrar errores de sintaxis
    use namespace::autoclean;

    has 'name' => (
                is         => 'rw',
  isa        => 'Str',
                reader => 'getName',
                writer => 'setName',
    );

no Moose;
__PACKAGE__->meta->make_immutable; #no voy a cambiar mi clase
1;

#File: Developer.pm
package Developer;

    use Moose;
    use strict; #Obliga a la programación segura y definición de variables
    use warnings; #Ayudará a encontrar errores de sintaxis
    use namespace::autoclean;

    extends 'Person'; #SUBCLASSING, hereda de Person

    has 'skill' => (
                is         => 'rw',
               isa        => 'Str',
                reader => 'getSkill',
                writer => 'setSkill',
    );
 
no Moose;
__PACKAGE__->meta->make_immutable; #no voy a cambiar mi clase
1;

#.............................................................................................................................
#File: script_subclassing.pl
#!/usr/bin/perl
use strict;
use warnings;
use Moose;
use Developer; #Nuestra clase

my $instancia = Developer->new(name=>'Daro',skill=>'Perl developer');
print "Nombre: " . $instancia->getName() . "\n"; #return 'Daro'
print "Skill: " . $instancia->getSkill() . "\n"; #return 'Perl developer'
#..........................................................................................................................end


2) Herencia Múltiple (multiple inheritance)


#File: WriterMonkey.pm
package WriterMonkey;

    use Moose;
    use strict;
    use warnings;
    use namespace::autoclean;
 
    has 'keyBySeconds' => (
                is         => 'rw',
  isa        => 'Int',
                reader => 'getKeyBySeconds',
                writer => 'setKeyBySeconds',
    );

    sub writerCode {
        my ( $self ) = @_;
        print "Coding...     \n";
    }
 
no Moose;
__PACKAGE__->meta->make_immutable;
1;

#File: Developer.pm
package Developer;

    use Moose;
    use strict; #Obliga a la programación segura y definición de variables
    use warnings; #Ayudará a encontrar errores de sintaxis
    use namespace::autoclean;
 
    extends 'Person', 'WriterMonkey'; #multiple inheritance

    has 'skill' => (
                is         => 'rw',
  isa        => 'Str',
                reader => 'getSkill',
                writer => 'setSkill',
    );
 
no Moose;
__PACKAGE__->meta->make_immutable;
1;

#.........................................................................................................
#File: script_multiple_inheritance.pl
#!/usr/bin/perl
use strict;
use warnings;
use Moose;
use Developer; #Nuestra clase

my $instancia = Developer->new(name=>'Daro',skill=>'Perl developer', keyBySeconds=>60);
print "Nombre: " . $instancia->getName() . "\n"; #return 'Daro'
print "Skill: " . $instancia->getSkill() . "\n"; #return 'Perl developer'
$instancia->writerCode(); #print 'Coding...'
#..........................................................................................................................end

3) Clases Abstractas o Interfaces con métodos abstractos


Hay que tener en cuenta que ni Perl ni Moose ofrecen clases abstractas. Con Moose se puede definir una clase "interfaz única" con role (Moose::Role), que contiene solo una lista de los métodos requeridos (requires). Cualquier clase que consuma este role debe implementar todos los métodos necesarios, ya sea directamente o a través de la herencia. No se puede retrasar la implementación de los métodos requeridos para que puedan ser implementadas por subclases futuras.

#File: Printable.pm
package Printable; #Clase Interface/Abstracta
    use strict;
    use warnings;
    use Moose::Role;

    requires 'doPrint', 'doPrint2'; #Métodos abstractos
    #requires must be implemented by a subclass or consumer class

no Moose;
1;

#File: Paper.pm
package Paper;
    use Moose;

    with 'Printable'; #Implement la clase Printable

    has 'text' => (
  isa        => 'Str', #Tipo String
                reader => 'getText',
                writer => 'setText'
    );

    sub doPrint {
        my ( $self ) = @_;
        print "Doing 1 ... " . $self->getText() . "    \n";
    };

    sub doPrint2 {
        my ( $self ) = @_;
        print "Doing 2 ... " . $self->getText() . "    \n";
    };
    
    
no Moose;
1;

#File: script_test_interface.pl
#!/usr/bin/perl
use strict;
use warnings;
use Moose;
use Paper; #Nuestra clase que implementa la interface Printable

my $instancia = Paper->new(text=>'texto a immprimir.');
$instancia->doPrint();
$instancia->doPrint2();



Referencias:
-Blog: Getting Started with Moose.
-Moose::Manual::Classes.
-Roles_Versus_Abstract_Base_Classes.
-Moose Manual.



Perl: POO con Moose, Estructura de datos

Estructura de datos con Moose

Las clases en Moose (con perl 5) pueden tener estructuras de datos como atributos usando Types en la definición del isa.

1) Clase con Atributos Hash

#This is perl 5, version 14, subversion 2 (v5.14.2)
#File: MyHash.pm
package MyHash;

    use Moose;
    use strict;
    use warnings;
    use namespace::autoclean;

    has 'myHashRef' => (
is => 'rw',
isa => 'HashRef',
reader  => 'getMyHashRef',
writer  => 'setMyHashRef',
default => sub {
return {
'0' => "first",
'1' => "second"
}
                                    }
                     );

    sub printOptions {
        my ( $self ) = @_;
        my $str = $self->getMyHashRef->{'0'};
        $str .= "\n";
        $str .= $self->getMyHashRef->{'1'};
        $str .= "\n";
        print $str;
    }

no Moose;
__PACKAGE__->meta->make_immutable;
1;

#................................................................................................
#File: script_test_MyHash.pl
#!/usr/bin/perl
use strict;
use warnings;
use MyHash;

my $instancia = MyHash->new();
$instancia->printOptions();
$instancia->setMyHashRef({'0' => "primero", '1' => "segundo"});
$instancia->printOptions();
#.............................................................................................end



Referencias:
-Types in Moose.
-Attribute Native.


jueves, 25 de septiembre de 2014

Perl: POO con Moose, Básico

Programación Orientada a Objetos en Perl con Moose

Para programar OO con Perl se puede usar la vieja escuela con perlobj (mediante un mecanismo conocido como bendición) o usar algo más moderno como uno de los sistemas de POO para Perl: Moose, Moo (Minimalist Object Orientation Moose compatible), Class::Accessor, Class::Tiny, Role::Tiny o Perl 6 OO (en el futuro). Aquí vamos a usar Moose. Moose es un "postmodern object system for Perl 5" que hace más amigable la POO que la vieja escuela de perlobj.  En la vieja escuela era necesario crear el método new de las clases, en cambio con Moose no es necesario porque las clases heredan de Moose::Object quien ya implementa el new. O sea que prescindimos de la creación de constructores new.


Instalar Moose



Se debe por lo menos tener instalado Perl 5.8, pero es preferible 5.10 o 5.12. Moose se instala fácilmente con CPAN:

cpan Moose
#o se puede usar: sudo perl -MCPAN -e 'install Moose'
#o también: sudo apt-get install libmoose-perl

Ejemplos de Clases Moose:


1) Una Clase con Atributo String


#File: NameStr.pm
package NameStr;

    use Moose;
    use strict; #Obliga a la programación segura y definición de variables
    use warnings; #Ayudará a encontrar errores de sintaxis
    use namespace::autoclean;

    has 'name' => (
                is         => 'rw', #Lectura-Escritura. También se puede usar 'ro' = read-only
  isa        => 'Str', #Tipo String (es obligatorio el valor string)
    );

    sub myNameIs
    {
        my $self = shift;
        my $myname = $self->name();
        print "My name: $myname \n";
    }


no Moose;
__PACKAGE__->meta->make_immutable; #no voy a cambiar mi clase
1; # Don't forget "1;" at end to return a true value from the file.
=pod
Nota 1: el  "isa  => 'Str'" hace que sea obligatorio que cuando se setea el valor el mismo sea string. Si se quiere que acepte un Undef lo que se debe poner es "isa => 'Maybe[Str]'".
Nota 2: Poner make_immutable junto con autoclean es una buena práctica Moose.
=cut

#...........................................................
#File: script_NameStr.pl
#!/usr/bin/perl
use strict;
use warnings;
use Moose;
use NameStr; #Nuestra clase

my $instancia = NameStr->new();
$instancia->name('Daro');
$instancia->myNameIs();
#......................................................End

2) Una Clase con Atributo String y getter-setter

#Se puede usar getter and setter estilo Java

#File: NameStr.pm
package NameStr;

    use Moose;
    use strict; #Obliga a la programación segura y definición de variables
    use warnings; #Ayudará a encontrar errores de sintaxis
    use namespace::autoclean;

    has 'name' => (
                is         => 'rw', #Lectura-Escritura
  isa        => 'Str', #Tipo String
                reader => 'getName', #getter
                writer => 'setName', #setter
    );

    sub myNameIs
    {
        my $self = shift;
        my $myname = $self->getName(); #getter
        print "My name: $myname \n";
    }


no Moose;
__PACKAGE__->meta->make_immutable; #no voy a cambiar mi clase
1;

#...........................................................
#File: script_NameStr.pl
#!/usr/bin/perl
use strict;
use warnings;
use Moose;
use NameStr; #Nuestra clase

my $instancia = NameStr->new();
$instancia->setName('Daro'); #setter
$instancia->myNameIs();
#......................................................End

3) Una clase con atributo Integer


#File: AgeInt.pm
package AgeInt;

    use Moose;
    use strict; #Obliga a la programación segura y definición de variables
    use warnings; #Ayudará a encontrar errores de sintaxis
    use namespace::autoclean;

    has 'age' => (
                is         => 'rw', #Lectura-Escritura
  isa        => 'Int', #Tipo Integer
                default =>  37            
    );


no Moose;
__PACKAGE__->meta->make_immutable; #no voy a cambiar mi clase
1;

#...........................................................
#File: script_AgeInt.pl
#!/usr/bin/perl
use strict;
use warnings;
use Moose;
use AgeInt;  #Nuestra clase

my $instancia = AgeInt->new();
print $instancia->age() . "\n";
$instancia->age(19);
print $instancia->age() . "\n";
#......................................................End

4) Propiedades de atributos


#File: NameStrAtr.pm
package NameStrAtr;

    use Moose;
    use strict; #Obliga a la programación segura y definición de variables
    use warnings; #Ayudará a encontrar errores de sintaxis
    use namespace::autoclean;

    has 'name' => (
                is         => 'rw', #Lectura/Escritura
  isa        => 'Str', #Tipo String
                reader => 'getName',
                writer => 'setName',
                required => 1, #Es requerido y no permite el valor 'undef'
                clearer   => 'clearName', #permite limpiar el valor, provoca que hasName devuelva false
                predicate => 'hasName', #devuelve true si tiene un valor
                lazy    => 1, #no se inicializa hasta que se llama al método lector
                default => '',
                init_arg => 'elNombre' #Nombre con el cual se referencia desde el constructor
    );

no Moose;
__PACKAGE__->meta->make_immutable; #no voy a cambiar mi clase
1;

#.............................................................................................................
#File: script_NameStrAtr.pl
#!/usr/bin/perl
use strict;
use warnings;
use Moose;
use NameStrAtr; #Nuestra clase

my $instancia = NameStrAtr->new(elNombre=>'Daro'); #required
print "Nombre: " . $instancia->getName() . "\n"; #return 'Daro'
$instancia->setName('Daro Andres');
print "Nombre: " . $instancia->getName() . "\n"; #return 'Daro Andres'
print "Has value?: " . $instancia->hasName() . "\n"; #return 1 (true)
$instancia->clearName(); #Limpia el valor
print "Has value?: " . $instancia->hasName() . "\n"; #return (false)
#........................................................................................................End

5) Inicializadores de atributos con Builder   


#File: NameStrBuilt.pm
package NameStrBuilt;

    use Moose;
    use strict; #Obliga a la programación segura y definición de variables
    use warnings; #Ayudará a encontrar errores de sintaxis
    use namespace::autoclean;

    has 'name' => (
                is         => 'rw', #Lectura/Escritura
  isa        => 'Str', #Tipo String
                reader => 'getName',
                writer => 'setName',
                builder   => 'buildName'

    );

    #Constructor inicializador del atributo name
    sub buildName {
        my $self = shift;
        $self->setName('Built Name (Nombre construido)'); #Inicializa
    }

no Moose;
__PACKAGE__->meta->make_immutable; #no voy a cambiar mi clase
1;

#.............................................................................................................
#File: script_NameStr.pl
#!/usr/bin/perl
use strict;
use warnings;
use Moose;
use NameStrBuilt; #Nuestra clase

my $instancia = NameStrBuilt->new();
print "Nombre: " . $instancia->getName() . "\n"; #return 'Built Name (Nombre construido)'
#........................................................................................................End

6) Disparadores trigger en atributos

Un disparador es una función que es llamada cada vez que se cambia el atributo.

#File: NameStrTrigged .pm
package NameStrTrigged;

    use Moose;
    use strict; #Obliga a la programación segura y definición de variables
    use warnings; #Ayudará a encontrar errores de sintaxis
    use namespace::autoclean;

    has 'name' => (
                is         => 'rw', #Lectura/Escritura
  isa        => 'Str', #Tipo String
                reader => 'getName',
                writer => 'setName',
                trigger => \&triggerForSetName, #referencia a la función que se va a disparar cuando se setea el valor

    );

    #El trigger se dispara despues que se setea el atributo
    sub triggerForSetName {
        my ( $self, $name, $old_name ) = @_;
        if ($old_name){
            print "Trigger executed... new: ".$name." old: ".$old_name."\n";
        }
    }
 
no Moose;
__PACKAGE__->meta->make_immutable; #no voy a cambiar mi clase
1;

#.............................................................................................................
#File: script_NameStr.pl
#!/usr/bin/perl
use strict;
use warnings;
use Moose;
use NameStrTrigged; #Nuestra clase

my $instancia = NameStrTrigged->new(name=>'Nombre inicial');
print "Nombre: " . $instancia->getName() . "\n"; #return 'Built Name (Nombre construido)'
$instancia->setName('Segundo nombre');
print "Nombre: " . $instancia->getName() . "\n"; #return 'Built Name (Nombre construido)'
=pod
Se imprime en pantalla:
Nombre: Nombre inicial
Trigger executed... new: Segundo nombre old: Nombre inicial
Nombre: Segundo nombre
Presione una tecla para continuar . . .
=cut
#........................................................................................................End


Bueno, así vimos un resumen general del uso de clases con Moose.


Referencias:
http://en.wikibooks.org/wiki/Programming_with_Moose
https://dl.dropboxusercontent.com/u/45670449/Moose_Manual.pdf
http://modernperlbooks.com/books/modern_perl/chapter_07.html
https://www.perl.org/about/whitepapers/perl-object-oriented.html
https://metacpan.org/pod/Moose::Manual
http://perlmaven.com/object-oriented-perl-using-moose
https://metacpan.org/pod/Moo
http://perldoc.perl.org/perlootut.html#Role%3a%3aTiny

martes, 27 de agosto de 2013

Perl: Paso de parámetros por referencia

Paso de parámetros por referencia en Perl

Cuando invocamos una subrutina y le pasamos parámetros en realidad le estamos pasando una lista de datos, que se llama @_ . Cuando pasamos vectores (matrices, arreglos o arrays ) o tablas asociativas ( hashes ) como parámetros, en realidad los estamos introduciendo, elemento por elemento, en @_ . La forma más económica de pasar parámetros a subrutinas es pasarlos por referencia. De esta manera no pasamos los datos en sí, si no la dirección que ocupan en memoria. Así no es necesario enumerar y copiar todos los datos a @_, y evitar los problemas de pasar varios hashes o arreglos, y la subrutina que reciba las referencias puede acceder a los datos en su organización original, ya sean escalares, vectores o tablas asociativas, las tres clases de variables en Perl. Por otro lado el paso por referencia permite modificar de forma permanente, no local, los datos pasados como argumento.

1) Ejemplo de paso por referencia

#
# Ejemplo de paso de parámetros por referencia en Perl:
# ¿Como pasar parámetros por referencia y modificar los valores?
# How to pass parameters by reference in perl, modify the values​​?
#This is perl 5, version 14, subversion 2 (v5.14.2)
#!/usr/bin/perl

#use strict;
#use warnings;

my $param = "algo";
my @vector1 = (1,2,3);
function_with_params(\$param, \@vector1);
print "\n";
print $param;
print "\n";
print $vector1[0];
print "\n";

sub function_with_params{
    my ($arg1, $arg2) = @_;
    ${$arg1} = "changed...";
    @{$arg2}[0]=33;    #vector1
    return;
    }

2) Ejemplo de paso por referencia de un array.

#!/usr/bin/perl
use strict;
use warnings;

print "Ejemplo perl de paso por referencia de un array... \n";

my @airlines_travel = ("a","b","b","c","k");
my $arrayRef = \@airlines_travel; #referencia al array
my $string = "b";

print "Count: " . howManyTimesIsString($string, $arrayRef) . "\n";

# Cuenta cuantas veces esta un string en un array
sub howManyTimesIsString {
 my ($string, $arrayRef) = @_;
 my $count = 0;
 foreach my $item (@{$arrayRef}) {
   if ($string eq $item) {
      $count++;
   }
 }
 return $count;
}

3) POO y paso por referencia.


En perl todos los objetos son una referencia. Es decir, cuando tenes un $obj es una variable scalar que simplemente mantiene la referencia al objeto. Cuando pasamos un objeto como parámetro lo que estamos pasando es su referencia (no es necesario hacer nada extraño para explicitar esto).

También se puede explicitar usando \variableObject y $$variableObject pero no es recomendable usarlo de esta manera. A continuación un ejemplo de esta forma:

#This is perl 5, version 14, subversion 2 (v5.14.2)
#...

sub metodo1{
  my ($self) = @_;

  my $obj = Example->new();
  my $o = $self->metodo2(\$obj);
  print $o->getName();
  return;
}

sub metodo2{
  my ($self, $obj) = @_;
#...
  print $$obj->encodeHTMLtoUTF8($str);
  $$obj->setName("modificado");
  return $$obj;
}



Referencias:
-Paso de parámetros por valor y por referencia (Perl).
-Blog: Parametros por referencia en perl.




lunes, 29 de abril de 2013

Perl: Read a Table from database using DBI

¿How to read a Table from database using DBI? 

#!/usr/bin/perl -w

use strict;
use warnings;
use DBI;

use constant DATABASE => "mydatabase";
use constant HOSTNAME => "myhostname";
use constant USERNAME => "user";
use constant PASSWORD => "123";

my $dbh = db_connect();

print "\nRead MyTable table : \n";

my $rows = read_table($dbh);
my $affected_rows = print_table($dbh, $rows);
print "Affected rows: $affected_rows: \n";

#
sub read_table {
    my $dbh = shift;

    my $sql1 = qq(
        SELECT * FROM MyTable

    );
    my $sth1 = $dbh->prepare_cached( $sql1 );
    $sth1->execute();
    my $sql_return = $sth1->fetchall_arrayref( {} );
       
    return $sql_return;
}

#
sub print_table {
    my $dbh = shift;
    my $rows = shift;

    foreach my $row (@$rows) {       
          print "$row->{
columnName_01}\n";
          print "$row->{columnName_02}\n";  
        }

  my $arraySize = scalar (@$rows);
  return $arraySize;
   
}
   
sub db_connect {
   
    my $db   = DATABASE;
    my $host = HOSTNAME;
    my $user = USERNAME;
    my $pass = PASSWORD;

    my $dbh = DBI->connect(
        join(':', 'dbi:mysql', $db, $host), $user, $pass,
        { AutoCommit => 1, PrintError => 1, RaiseError => 1 },
    );

    return $dbh;
}

viernes, 26 de abril de 2013

Perl: Modules installing on Ubuntu system

¿What Perl Modules Already Installed On My System?
¿Qué módulos tengo instalado en el sistema?

How to list installed perl module? List installed perl module:

$ instmodsh

Available commands are:
   l            - List all installed modules
   m <module>   - Select a module
   q            - Quit the program
cmd? l
Installed modules are:
   Class::Load
   Data::OptList
   Dist::CheckConflicts
   ExtUtils::MakeMaker
   List::MoreUtils
   MRO::Compat
   Module::Implementation
   Module::Runtime
   Mojolicious
   Package::DeprecationManager
   Package::Stash
   Package::Stash::XS
   Params::Util
   Perl
   Perl::Metrics::Simple
   String::Util
   Sub::Exporter
   Sub::Install
   Sub::Uplevel
   Test::Deep
   Test::Exception
   Test::Fatal
   Test::NoWarnings
   Test::Requires
   Test::Tester
   Try::Tiny
   local::lib


Other way:
 
perl -e 'while (<@INC>) { while (<$_/*.pm>) { print "$_\n"; } }'
 
Show all perl paths:
 
perl -E 'say join "\n", @INC'
 
Find a file: 
sudo find / -type f -name 'Example.pm'
 
 
¿What Know if a Perl Modules Already Installed On My System?

perl -MNameModule -e 1
If not installed throw error "Can' locate module....."

For example: 
perl -MException::Base -e 1
perl -MLog::Log4perl -e 1

Install using CPAN:


For example:

sudo perl -MCPAN -e 'install IO::EventMux'
sudo perl -MCPAN -e 'install Log::Log4perl'
sudo perl -MCPAN -e 'install Test::Class'
sudo perl -MCPAN -e 'install Log::Dispatch'
sudo perl -MCPAN -e 'install Params::Validate'
sudo perl -MCPAN -e 'install DBD::mysql'
sudo perl -MCPAN -e 'install JSON::XS'
sudo perl -MCPAN -e 'install Cache::Memcached'  

sudo perl -MCPAN -e 'install Thread'    
sudo perl -MCPAN -e 'install Thread::Pool'

sudo perl -MCPAN -e 'install Exception::Base'
sudo perl -MCPAN -e 'install XML::LibXML' 

Install using System:

For example:

sudo apt-get install libtest-class-perl
sudo apt-get install liblog-dispatch-perl
sudo apt-get install libparams-validate-perl
sudo apt-get install libdbd-mysql-perl
sudo apt-get install libjson-xs-perl
sudo apt-get install libjson-perl
sudo apt-get install libjson-any-perl
sudo apt-get install libcache-memcached-perl

sudo apt-get install libnumber-format-perl
sudo apt-get install libtest-log-dispatch-perl
sudo apt-get install libconfig-inifiles-perl
sudo apt-get install libwww-perl
sudo apt-get install libdigest-md5-perl
sudo apt-get install libproc-daemon-perl
sudo apt-get install libxml-simple-perl

sudo apt-get install libxml-libxml-perl

¿Cómo saber si tenemos un módulo instalado?

Si Module::Util está instalado, use pm_which:
:~$ pm_which EL::Modulo

Use perldoc, pues para saber si un módulo está instalado y donde se encuentra (supuesto que el módulo contiene documentación en su interior) use perldoc -l:
:~$ perldoc -l EL::Modulo

También puede comprobar la existencia cargando el módulo:
:~$ perl -MEL::Modulo -e 1

Instale pmtools y use el comando pminst (Se puede obtener en http://search.cpan.org/~mlfisher/pmtools/.)

Sigue un ejemplo de uso:
pp2@nereida:~/src/perl/IPC-PerlSSH/lib/IPC$ pmdesc EL::Modulo # descripción

pp2@nereida:~/src/perl/coro$ pminst odulo
EL::Modulo
pp2@nereida:~/src/perl/IPC-PerlSSH/lib/IPC$ pmload EL::Modulo  # Que modulos carga

Módulos en el Núcleo de Perl:
:~> perl -MModule::CoreList -e \
   'print Module::CoreList->first_release("Data::Dumper")."\n"'


Referencias:-Saber que Módulos están Instalados: http://www.davioth.com/lhp/node188.html