SPUG: Switch's "case" matching doesn't set $1 !

Eric Wilhelm scratchcomputing at gmail.com
Tue Feb 13 13:50:44 PST 2007

# from Tim Maher
# on Tuesday 13 February 2007 11:56 am:

>On Tue, Feb 13, 2007 at 11:13:13AM -0800, Eric Wilhelm wrote:
>> There, you'll see that it is indeed the "if/elsif/elsif/else"
>> lexical structure that you might expect from the input structure,
>> but rather than doing "$_ =~ m/.../" in the if(), it ships the
>> regexp off to the case() function
>... which, AFAICT (see below), then does the "$_ =~ m/.../"
>> Had it been implemented as a DSL of prototyped functions (sub case
>> ($&) {...}, then the capture might work because your code would get
>> executed within scope of the match.

On further reflection, I realize that prototype wouldn't work, and 
source filtering is probably still required to get 'continue' and such 
supported.  However, it still needs to do something like

  if(type_check($input, 'Regexp') and $_ =~ m/$input/) {

So, you would source filter to generate something like:

    # these array refs contain the original code, but with some munging
    # of next, last, continue
    [/(vanilla|chocolate)/, sub { # () sets $1 ??
                print "The flavor of the moment is: $1"; # what's $1?
	sub {
                print "'$_' is not a real flavor!";

switch_impl() would then pass the $check and $subref from each pair to 
case_impl() or something.  Some shared variables would probably be 
needed for 'continue' and such.  Fun.

But, is the Perl 6 given() supposed to give you the match variables in 
the when() block?  If so, you should file a patch in rt against 

>To produce the effect I'm expecting, it's not necessary for the
>match to be executed within the scope of the user's code--just
>for the match to be left in $1--which, as part of the package
>"main", is always in scope.

from perlre: "The numbered match variables ($1, $2, $3, etc.) and the 
related punctuation set ($+, $&, $`, $', and $^N) are all dynamically 
scoped until the end of the enclosing block or until the next 
successful match, whichever comes first."

>This program demonstrates that () symbols can be recognized when
>delivered via  variables:
> perl -wle '$re=".(.)."; "abc" =~ /$re/ and print $1' # prints: b

$ perl -Mstrict -we 'my $v = "abc";
  sub matchit {return($_[0] =~ m/$_[1]/)};
  warn matchit($v, qr/(abc)/);
  warn "see \$1?  ", defined($1) ? $1 : "nope"'
abc at -e line 1.
see $1?  nope at -e line 1.

"But as to modern architecture, let us drop it and let us take
modernistic out and shoot it at sunrise."
--F.L. Wright

More information about the spug-list mailing list