[Melbourne-pm] Perl switch statements

Mathew Robertson mathew.blair.robertson at gmail.com
Mon Oct 22 17:04:33 PDT 2012


> > What is also surprising is this:
> >
> > sub moo {
> >   given (shift) {
> >     when ('ay') { "yay" }
> >     when ('bee') { "hurrah" }
> >     default { "what?" }
> >   };
> >   say $_;
> > }
> > moo("bee");
> >
> >
> > I thought the when() implemented the test against $_...
>
> It does.  $_ is local to the given block, same as a foreach loop.
>

I always thought that "unless $_ is explicitly localised"... would
manipulate the global $_

foreach (1..2) {
  foreach ('a'..'c') {
    print $_." ";
    last;
  }
  print $_." ";
}
print $/;

ie: the output is  "a 1 a 2"... on v5.14 and v5.8.8

... I could have sworn that I have used that idiom in the past, expecting
to get "a a a a"...

but there you go.

To clarify, I would have expected $x to not be lexical... I am deliberately
reusing $x in the child scope assignment, without localising $x (via 'my'
or 'local'):

my $x = 'foo';
foreach $x (1..2) {
  foreach $x ('a'..'c') {
    print $x." ";
  }
  print $x." ";
}
print $x.$/;

gives: a b c 1 a b c 2 foo
when I told the code to generate: a b c c a b c c c



>
> > or even:
> >
> > sub moo {
> >   given (shift) {
> >     when ('ay') { "yay" }
> >     when ('bee') { $_ = "hurrah" }
> >     default { "what?" }
> >   };
> >   say $_;
> > }
> > moo("bee");
>
> Same deal.  $_ can't escape the given block.  If it did, nested givens
> would
> clobber each other.
>

I'm going to say either a) no it wouldn't, or b) that is expected......
depending on the use case.

ie: either you are in block scope so other 'when's arn't executed, or you
are explicitly manipulating $_ so that you can deliberately could cause
manipulation of the outer scope.



In any case, the point is moot as $_ or $x are localised to the scope - and
we (well 'I') learnt something new.

cheers,
Mathew

>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.pm.org/pipermail/melbourne-pm/attachments/20121023/160d42ab/attachment-0001.html>


More information about the Melbourne-pm mailing list