Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Given When Syntax

by LanX (Archbishop)
on Mar 15, 2014 at 18:27 UTC ( #1078474=note: print w/replies, xml ) Need Help??


in reply to Given When Syntax

> If I can't get this to work, I'll be stuck using an if/elsif construct

a little syntactic sugar with an improvised in operator and given/when has no better readability anymore.

use strict; use warnings; sub in { for my $val (@_) { return 1 if $_ eq $val; } return; } sub test1 { my ($var) = @_; my $i; for ($var) { if ( in 1 ) { $i = "One" } elsif ( in 2 ) { $i = "Two" } elsif ( in 3,4,5 ) { $i = "Three, Four or Five" } else { $i = "Other" } } print "$var is $i\n"; } sub test2 { my ($var) = @_; my $i; for ($var) { if ( in 1 ) { $i = "One" ;next} if ( in 2 ) { $i = "Two" ;next} if ( in 3,4,5 ) { $i = "Three, Four or Five" ;next} $i = "Other" } print "$var is $i\n"; } test1($_) for 1..6; test2($_) for 1..6;

) though I think it's still faster, it might be able to automatically optimize to hash-lookups

Cheers Rolf

( addicted to the Perl Programming Language)

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1078474]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (6)
As of 2019-03-22 22:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How do you Carpe diem?





    Results (114 votes). Check out past polls.

    Notices?