Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: Switch/case (given/when) in Perl5

by Roy Johnson (Monsignor)
on Mar 23, 2005 at 15:21 UTC ( [id://441792]=note: print w/replies, xml ) Need Help??


in reply to Switch/case (given/when) in Perl5

Developing this, I originally wanted to have the simpler syntax of when {cond-block} {then-block} but prototypes won't let me do that. You can only get one block interpreted as an anonymous sub without specifying sub, so i had to introduce the then pseudokeyword.

The same thing is what makes the grep solution so clunky. So meditation #2: we need a qsub operator. You put blocks of code after it, and it gives you a list of coderefs back. Then the arguments to grep look like:

[qsub {/z/} { print "Hi!\n" }], [qsub {/o/} { print "Oh!\n" } 'break'], [qsub {1} { print "This is the default\n" }]
Ah, the 'break'. Well, its value doesn't matter, so I could just stick {} in there instead. Or parenthesize qsub's list and stick a comma before 'break'...or qsub could leave things that aren't in braces alone. Smart qsub. Want to include a hashref in your list? Stick a + on the front, or put it in parentheses.

Update: Hold the phone! You don't need a new operator! You just need new semantics: if a block appears before or after any other object in list context, and they're not separated by a comma, the block is a coderef. Normal executable blocks are in void context; hashrefs will either appear separated by commas or alone. Nothing breaks. Right? [Wrong: indexing of hashes breaks (or at least becomes ambiguous): (1, $hash {'index'}) — dang.] Hashrefs adjacent to coderefs can be disambiguated with the old + trick.


Caution: Contents may have been coded under pressure.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (2)
As of 2024-04-26 02:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found