SWITCH: question on evaluation

R

Robert

If I have a whole lot of cases in a SWITCH: statement does the whole
statement get parsed or does it exit on a first match?

I was just curious...

robert
 
P

Paul Lalli

Robert said:
If I have a whole lot of cases in a SWITCH: statement does the whole
statement get parsed or does it exit on a first match?

"parsing" is something that happens at compile time. That's how syntax
errors are found. I think you meant "does the whole statement get
*evaluated*?". For the answer to that, we turn to the documentation:

perldoc Switch
However, when a "case" block has been executed control is
automatically transferred to the statement after the
immediately enclosing "switch" block, rather than to the
next statement within the block. In other words, the success
of any "case" statement prevents other cases in the same
scope from executing. But see "Allowing fall-through" below.


We can see this behavior ourselves with a simple test:
#!/usr/bin/perl
use strict;
use warnings;
use Switch;

sub foo{
print "Foo() being evaluated\n";
return 5;
}

sub bar {
print "Bar() being evaluated\n";
return 10;
}

sub baz {
print "Baz() being evaluated\n";
return 15;
}

my $foo = 10;

switch ($foo){

case foo() {print "matched to foo()\n";}
case bar() {print "matched to bar()\n";}
case baz() {print "matched to baz()\n";}
}

__END__
Foo() being evaluated
Bar() being evaluated
matched to bar()


From the above, it is apparent that the third case is never evaluated.
I was just curious...

Hope this helps,
Paul Lalli
 

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,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top