Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re: Using Number Ranges in a Dispatch Table

by afoken (Prior)
on Feb 18, 2012 at 18:46 UTC ( #954780=note: print w/ replies, xml ) Need Help??


in reply to Using Number Ranges in a Dispatch Table

The map trap. Run this:

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %oops=( A => 1, map { $_ => 2 } ('B','C'), map { $_ => 3 } ('D','E'), F => 4, ); print Dumper(\%oops);

Look at the output. Then add ( ) around each map expression:

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %oops=( A => 1, (map { $_ => 2 } ('B','C')), (map { $_ => 3 } ('D','E')), F => 4, ); print Dumper(\%oops);

Alexander

--
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)


Comment on Re: Using Number Ranges in a Dispatch Table
Select or Download Code
Re^2: Using Number Ranges in a Dispatch Table
by planetscape (Canon) on Feb 18, 2012 at 19:32 UTC

    Bless you!

    I thought the technique itself should be sound, and the solution something simple, but I didn't realize it would be this simple!

    Thanks!

    HTH,

    planetscape
      No need to double up on the parentheses
      (map { $_ => 2 } 'B','C'), (map { $_ => 3 } 'D','E'),
        If we're being nitpicky :) no need to create a lexical block for map:
        $ perl -Mstrict -MData::Dumper -we'my%h=( (map +($_=>2), "B","C","D"), + one=>1 ); print Dumper(\%h)' $VAR1 = { 'one' => 1, 'D' => 2, 'C' => 2, 'B' => 2 };
Re^2: Using Number Ranges in a Dispatch Table
by oko1 (Deacon) on Feb 19, 2012 at 17:06 UTC

    But isn't this always the case when you're dealing with statements that take lists as arguments?

    # Ooops! print join ",", @foo, "\n"; # Ooops! print grep /o/, @foo, "Hello world!\n"; # Ooops! print table{ map { tr(td($_->[0]), td($_->[1])) } @foo, ...

    My rule of thumb is, if one of these statements is followed by anything besides its argument, then parenthesize that statement's entire argument list.

    # De-oopsed. print join(",", @foo), "\n"; print grep(/o/, @foo), "Hello world!\n"; print table{ map({ tr(td($_->[0]), td($_->[1])) } @foo), ...
    -- 
    I hate storms, but calms undermine my spirits.
     -- Bernard Moitessier, "The Long Way"

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (14)
As of 2015-07-02 22:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (45 votes), past polls