Switch and capturing regexes

J

Joe Gottman

I am having problem using Switch with capturing regexes. For instance,
consider the following code:

use Switch;
my $foo = 'foo';
switch ($foo) {
case /(.*)/ {print "Worked. Captured text = '$1'\n";}
else {print "Didn't work\n";}
}

The output I get is
Worked. Captured text = ''

Thus, the regular expression is matching as expected, but no data is being
captured.



Joe Gottman
 
S

Steven Kuo

I am having problem using Switch with capturing regexes. For instance,
consider the following code:

use Switch;
my $foo = 'foo';
switch ($foo) {
case /(.*)/ {print "Worked. Captured text = '$1'\n";}
else {print "Didn't work\n";}
}

The output I get is
Worked. Captured text = ''

Thus, the regular expression is matching as expected, but no data is being
captured.




Perhaps the $1 you expected is no longer in scope when the block of
code following 'case' is executed? You'd have to look at source code
of the Switch module to verify that but this would seem to point in
that direction:


use Switch;
my $foo = 'foo';
$_ = 'foobar';
$_ =~ /(.{3})$/; # $1 = "bar";

my $save;

switch ($foo) {
case /(.+)(?{ $save = $1 })/ {print "Worked. Captured text = $save $1\n";}
else {print "Didn't work\n";}
}


By the way, /(.*)/ will match any string -- was that used
intentionally on your part?
 
J

Joe Gottman

Steven Kuo said:
Perhaps the $1 you expected is no longer in scope when the block of
code following 'case' is executed? You'd have to look at source code
of the Switch module to verify that but this would seem to point in
that direction:


use Switch;
my $foo = 'foo';
$_ = 'foobar';
$_ =~ /(.{3})$/; # $1 = "bar";

my $save;

switch ($foo) {
case /(.+)(?{ $save = $1 })/ {print "Worked. Captured text = $save
$1\n";}
else {print "Didn't work\n";}
}


By the way, /(.*)/ will match any string -- was that used
intentionally on your part?

Yes, I just wanted to demonstrate the concept. Thanks for your help.

Joe Gottman
 
T

topgunroot

$1, $2... swallowed in module Switch. :)) it is visible only in module
"Switch" itself.

actually, you can only handle result returned from internal functions
in Switch. I mean $val in switch($val)....

Don't believe it? just turn on debugger
....... perl -d yourscript

Allen
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top