Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: What I Most Recently Learned in Perl, But Should Have Already Known

by gawatkins (Monsignor)
on Aug 17, 2006 at 16:29 UTC ( #567959=note: print w/ replies, xml ) Need Help??


in reply to What I Most Recently Learned in Perl, But Should Have Already Known

unless, once I learned it, I quit having to create complex if-else statements to decide if something did not happen. All languages should have an equivalent to unless

Thank you,
Greg W


Comment on Re: What I Most Recently Learned in Perl, But Should Have Already Known
Re^2: What I Most Recently Learned in Perl, But Should Have Already Known
by izut (Chaplain) on Aug 17, 2006 at 17:28 UTC

    Continuing the if-else statements problem, the idiom I like most is:

    my $function = 'a'; my %functions = ( 'a' => sub { ... }, 'b' => sub { ... }, ); $functions{$function}->();

    It's amazing how this replace an entire switch or if-else statements.

    Igor 'izut' Sutton
    your code, your rules.

      I always run into the problem of the default case when I use that -- what if $function isn't a key in %functions? The error message "Undefined subroutine &main:: called" can be very difficult to figure out.

      And the straightforward fix isn't all that pretty:

      ($functions{$function} || $functions{default})->();
      But I admit that I still use it. With comments, if there is any chance that someone with a capacity to do me bodily harm might read the code.

        I think this way is prettier.

        sub do_something { my ($function) = @_; $function = 'default' unless exists $functions{$function}; $functions{$function}->(); }

        Igor 'izut' Sutton
        your code, your rules.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://567959]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (2)
As of 2014-09-20 15:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (160 votes), past polls