Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
As others have said here, perl does not have a built-in switch statement. However, TheDamian has written an excellent module (which will be a standard core module in future perl versions) called Switch.pm. It's very nice and perlish in the way it handles things (e.g. it doesn't treat everything like an int as the 'C' switch does). For example (from the module docs):
use Switch; switch ($val) { case 1 { print "number 1" } case "a" { print "string a" } case [1..10,42] { print "number in list" } case (@array) { print "number in list" } case /\w+/ { print "pattern" } case qr/\w+/ { print "pattern" } case (%hash) { print "entry in hash" } case (\%hash) { print "entry in hash" } case (\&sub) { print "arg to subroutine" } else { print "previous case not true" } }

Update: Here's an example similar to yours that might get you started. However, as talexb and japhy both mentioned, using coderefs in your hash might be a cleaner way of doing this.

use strict; use warnings; use Switch; my %house = ('CC' => 'My Name', 'AB' => 'AB Name', 'CD' => 'My friend', 'EF' => 'Who?'); foreach my $person (keys %house) { print "$person: "; switch($person) { case 'AB' { print "Mine!\n" } case 'CC' { print "Yours!\n" } case 'CD' { print "Friend!\n" } case %house { print "in house, but don't know him!\n" } else { print "I don't know what to do!\n" } } }

In reply to (RhetTbull) Re: something like switch(case) in Perl by RhetTbull
in thread something like switch(case) in Perl by agustina_s

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2024-04-20 11:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found