On Wed, Oct 15, 2008 at 03:17, Marko Krstic <[EMAIL PROTECTED]> wrote:
> Hello,
>
> What is the best (shortest) way to define a hash where different keys have
> same values:
>
> %my_hash = { 1 => 'something', 2 => 'something', 3 => 'something else'};
>
> Is there a way to write something like:
>
> %my_hash = { 1,2 => 'something', 3 => 'something else', etc...}
>
> Thanks

I can think of two ways off the top of my head: use map* to build a
list (my prefered way) or use hash slice** notation and the repetition
operator***.

#!/usr/bin/perl

use strict;
use warnings;
use Data::Dumper;

#exploit the list nature of hash assignment
my %a = (
        one => 1,
        two => 2,
        map { $_ => 3 } qw<three four five six seven>
);

#use a hash slice
my %b = (
        one => 1,
        two => 2,
);
@b{qw<three four five six seven>} = (3) x 5;

print
        "a:\n", Dumper(\%a), "\n",
        "b:\n", Dumper(\%b), "\n",

* http://perldoc.perl.org/functions/map.html
** http://perldoc.perl.org/perldata.html#Slices
*** http://perldoc.perl.org/perlop.html#Multiplicative-Operators

-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to