given

Del libro Modern Perl:

The given construct is a feature new to Perl 5.10. It assigns the value of an expression to the topic variable and introduces a block:
  given ($name) {
    ...
  }
Unlike for, it does not iterate over an aggregate. It evaluates its value in scalar context, and always assigns to the topic variable:
  given (my $username = find_user())
given also makes the topic variable lexical to prevent accidental modification:

lhp@nereida:~/Lperl/src/perltesting$ cat -n given.pl 
     1  #!/usr/bin/env perl
     2  use Modern::Perl;
     3  
     4  given ('mouse') {
     5    say; 
     6    mouse_to_man( $_ ); 
     7    say;
     8  }
     9  
    10  sub mouse_to_man {
    11    $_ = shift; 
    12    s/mouse/man/;
    13    say "Inside mouse_to_man: $_";
    14  }
lhp@nereida:~/Lperl/src/perltesting$ ./given.pl 
mouse
Inside mouse_to_man: man
mouse
given is most useful when combined with when. given topicalizes a value within a block so that multiple when statements can match the topic against expressions using smart-match semantics.

Casiano Rodríguez León
Licencia de Creative Commons
Principios de Programación Imperativa, Funcional y Orientada a Objetos Una Introducción en Perl/Una Introducción a Perl
por Casiano Rodríguez León is licensed under a Creative Commons Reconocimiento 3.0 Unported License.

Permissions beyond the scope of this license may be available at http://campusvirtual.ull.es/ocw/course/view.php?id=43.
2012-06-19