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

#!/usr/bin/perl -w use strict; #This works fine. my %s = ( a => 1, b => 2); @s{ qw(first second third) } = qw(one two three); dumph(\%s); #How do I do it here? my $t = { a => 1, b => 2}; #$t->{ qw(first second third) } = qw(one two three); # doesn't work. #@$t->{ qw(first second third) } = qw(one two three); # doesn't work. #$$t{ qw(first second third) } = qw(one two three); # doesn't work. # You're perl monk solution goes here!! dumph($t); sub dumph { my $hashref = shift; while (my ($k, $v) = each %{ $hashref }) { print "$k => $v\n"; } }
Thanks! ~

Replies are listed 'Best First'.
Re: How do I use hashref slices?
by danger (Priest) on May 29, 2002 at 18:35 UTC
    @{$t}{qw/first second third/} = qw/one two three/; # or just: @$t{qw/first second third/} = qw/one two three/;
Re: How do I use hashref slices?
by Ovid (Cardinal) on May 29, 2002 at 18:37 UTC

    The syntax is clumsy:

    my $hashref = { one => 1, two => 2, three => 3 }; print @{$hashref}{qw/two three/};

    For your code:

    @{$t}{qw/first second third/} = qw(one two three);

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Re: How do I use hashref slices?
by Abigail-II (Bishop) on May 30, 2002 at 12:50 UTC
    The syntax for slicing in Perl is very, very simple:
    @{EXPRESSION} {LIST}
    (or with [LIST] if you're slicing an array.) EXPRESSION is an expression (or block) which evaluates to a reference to a hash (or array). As a special case, the EXPRESSION may be an identifier too. If the EXPRESSION is simple, one may leave the braces off.

    This explains how the presented solutions work.

    Abigail

Re: How do I use hashref slices?
by sfink (Deacon) on May 29, 2002 at 18:39 UTC
    @$t{qw(first second third)} = qw(one two three); @{$t}{qw(first second third)} = qw(one two three);
(crazyinsomniac) Re: How do I use hashref slices?
by crazyinsomniac (Prior) on May 30, 2002 at 01:18 UTC