in reply to fall through switch/case in perl

Your example problem is fairly simple, but for more complicated switch-like behavior,
my @switch_foo = ("a","b","c",...); for ($var) { my $junk = shift; while ($junk > 0) { print $switch_foo[$junk]); $junk--; } }
It's way overkill for your particular problem, but for commplicated situations, @switch_foo can contain references to subs, making it quite powerful (if a little slow).

In practice, however, if your algorithm needs a switch equivalent, you're better off re-thinking your algorithm.

Update: fixed the code so that it works!

--
$me = rand($hacker{perl});

Replies are listed 'Best First'.
Re^2: fall through switch/case in perl
by Anonymous Monk on Sep 07, 2004 at 15:23 UTC
    Your code will either not print anything, or it'll never finish printing.

    In practice, however, if your algorithm needs a switch equivalent, you're better off re-thinking your algorithm.

    Eh? And why is that? That's a pretty bold statement, considering many languages do have a 'switch', perl6 will have a switch, there's Switch.pm, both the manual and the FAQ discuss it (without dismissing it as choicing a bad algorithm), and it has been on the wishlist since the very first release of Perl in 1987.

      Your code will either not print anything, or it'll never finish printing.

      You're right, I forgot the $junk--; after the print statement.

      That's a pretty bold statement, considering many languages do have a 'switch', perl6 will have a switch, there's Switch.pm, both the manual and the FAQ discuss it (without dismissing it as choicing a bad algorithm), and it has been on the wishlist since the very first release of Perl in 1987.

      I never said switch was bad code. Perl6 will have a switch because a lot of people want it, and it is very readable. However, switch statements are unbelievably over-used. I stand by my statement; chances are, if your algorithm needs switch, you can come up with a better algorithm. There are, of course, a few exceptions.

      As to your "considering many languages have a 'switch'", multiplicity does not correctness make.

      --
      $me = rand($hacker{perl});
        I never said switch was bad code.

        You mean, people should rethink good code?

        As to your "considering many languages have a 'switch'", multiplicity does not correctness make.

        No, but it does mean your bold statement needs at least a shred of backup. Just stating "switch statements are unbelievably over-used" does not make correctness either. Back up your claim.