Yields: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" } }
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:Thanks!#!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";
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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |