dragonchild has asked for the wisdom of the Perl Monks concerning the following question:

I've got the following code:

my @keys = (1 .. 5); my @values = (6 .. 8); my %hash; @hash{@keys} = @values;
Now, what this does is assign undef to $hash{4} and $hash{5}. Is there a nice way I can do something like:

@hash{@keys} = @values || '';
That doesn't work, but that's what I'm trying to do ...

Replies are listed 'Best First'.
Re: Hash slices and too many keys
by merlyn (Sage) on Jul 28, 2001 at 03:31 UTC
    my @keys = (1..5); my @values = (6..8); my %hash; my @TEMP = @keys; # can use @keys if OK to mangle @hash{splice @TEMP, 0, @values) = @values; @hash{@TEMP} = ('') x @TEMP;

    -- Randal L. Schwartz, Perl hacker

Re: Hash slices and too many keys (Update cause I can't edit a root node)
by dragonchild (Archbishop) on Jul 27, 2001 at 23:55 UTC
    Update: I got the following to work, but it's really ugly...

    my @keys = (1 .. 5); my @values = (6 .. 8); my %hash; @hash{@keys} = (@values, ('') x (@columns - @values));
    There has to be a better way than that ...

      Well, the straight forward way would be

      foreach( 0 .. $#keys ) { $hash{ $keys{ $_ } } = $values{ $_ } || ''; }
Re: Hash slices and too many keys
by PrakashK (Pilgrim) on Jul 28, 2001 at 02:57 UTC
    How about:
    @hash{@keys} = (@values, ('') x @keys);
    Still ugly, but works.
Re: Hash slices and too many keys
by mongooser (Initiate) on Jul 28, 2001 at 03:26 UTC
    %hash = map {$_ => shift @values || ''} @keys;

    Sorry, couldn't think of a nice way to do it! :) But it works..
Re: Hash slices and too many keys
by premchai21 (Curate) on Jul 29, 2001 at 07:37 UTC
    TMTOWTDI:
    @hash{@keys} = map { ($_ > $#values) ? '' : $values[$_] } (0..$#keys);