Sometimes if ... elsif ... else really is the clearest, most effective way to do what you want. The code you've posted, I'd probably leave as-is, and go to something more advanced only as it got more hairy.

In Perl 5.10, you've got given ... when, which wold work really well here.

given ($line) { when ( m{\A Job: }xms ) { $job_details_info{Job} = $line } when ( m{\A File: }xms ) { push @files, $line } when ( m{\A Image }xms ) { $job_details_info{Image} = $line } }

Since your conditions are all patterns, a straight dispatch table might not be the way to go. I might write something like this:

use List::Util qw( first ); my @disp = ( { pattern => qr{\A Job: }xms, action => sub { $job_details_info{Job} = shift }, }, { pattern => qr{\A File: }xms, action => sub { push @files, shift }, }, { pattern => qr{\A Image }xms, action => sub { $job_details_info{Image} = shift }, } ); my $todo = first { $line =~ $_->{pattern} } @disp; if ( defined $todo ) { $todo->{action}->( $line ); } else { warn "no match: $line"; }

That's not really that much better than elsif, in my opinion, but it makes it possible to add more data to each case that it's testing, and you can then pass the data structure around to make it serve multiple purposes. For example, you might have a menu with user-visible text, conditions, and actions, and different parts of your program use different pieces of data, all in one structure that you can edit in one place.


In reply to Re: Multiple If Selections by kyle
in thread Multiple If Selections by est

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.