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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |