switch case (/regex/) ... $1 - emtpy

P

Petr Sezemsky

Hi,

Why using the regex in switch - case doesn't fill the $1, $2, ..
variables? This code works as I expect:

#!/usr/bin/perl
$_ = "hello world";

if (/he(ll)o/) {
print "OK: $1\n";
}

but the next doesn't work as the previous:

#!/usr/bin/perl
use Switch;
$_ = "hello world";

switch ($_) {
case (/he(ll)o/) {
print "OK: $1\n";
}
}

Thank you for explanation the problem.

Petr
 
U

Uri Guttman

PS> Why using the regex in switch - case doesn't fill the $1, $2, ..
PS> variables? This code works as I expect:

PS> #!/usr/bin/perl
PS> use Switch;

that module does source filtering. the actual code that compiles is not
what you put in the file. and because of that it is not recommended to
ever use that module.

PS> $_ = "hello world";

PS> switch ($_) {
PS> case (/he(ll)o/) {
PS> print "OK: $1\n";

you can't easily tell what the code is there and whether the regex is
run just before your print. it appears how you like it but it isn't
underneath.

perl 5.10 has given/when built in (taken from perl6) which is a proper
switch statement and it supports smart matching as well. this works as
you expect:

perl -le 'use feature ":5.10"; given ("bar") { when( /(a)/ ) { print "$1\n" } }'
a

see the docs in perlsyn for the full syntax.

uri
 

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,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top