Why doesn't this work?
switch ( $foo ) { case ( tr/I/I/ == 1 ) { $bar = 'low' } case ( tr/I/I/ == 2 ) { $bar = 'med' } case ( tr/I/I/ == 3 ) { $bar = 'high' } else { warn "Bad $_\n" } }
Yields:
Use of uninitialized value $_ in transliteration (tr///)

(Update: Because switch doesn't set $_, it filters the source code - in this case "insanely".)

Here's a test script:
#!perl! -w use strict; use Switch; my $foo = 'II'; print $foo =~ tr/I/I/, "\n"; my $bar; switch ( $foo ) { case ( tr/I/I/ == 1 ) { $bar = 'low' } case ( tr/I/I/ == 2 ) { $bar = 'med' } case ( tr/I/I/ == 3 ) { $bar = 'high' } else { $bar = "drat" } } print "Foo: $foo Bar: $bar\n"; # This works: switch ( $foo ) { case ( /I{3}/ ) { $bar = 'high' } case ( /I{2}/ ) { $bar = 'med' } case ( /I/ ) { $bar = 'low' } else { $bar = "drat" } } print "Foo: $foo Bar: $bar\n";
Thanks!

Update: Thanks kyle and jeffa, the lesson is learned - don't use Switch. (jeffa's solution indeed doesn't work - which surprised me)

Update2: moritz has it right, use the (5.010) given-when construct:

given ( $foo ) { when ( tr/I/I/ == 1 ) { $bar = 'low' } when ( tr/I/I/ == 2 ) { $bar = 'med' } when ( tr/I/I/ == 3 ) { $bar = 'high' } default { $bar = "drat" } }

In reply to switch, transliteration ( tr/// ) of $_ issue by whakka

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.