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 withwhen
.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