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?



No hay comentarios:

Publicar un comentario