Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Given When Syntax

by LanX (Saint)
on Mar 15, 2014 at 18:27 UTC ( [id://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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1078474]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (4)
As of 2024-03-28 21:07 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found