Assigning multiple hash entries with deref chain in front

K

Konrad Eisele

Assigning multiple hash with one statement is done with:
@a{'a','b'} = (1,2);
but how can I do it if I want to access the hash through
previous dereferences:
---------------------------
use Data::Dumper;
@a = ({'a'=>1,'b'=>2});
$b = \@a;
$b->[0]->{'a','b'} = (100,1000);
print Dumper(\@a);
---------------------------

$b->[0]->{'a','b'} = (1,2) doesn't work here.

How can I force list context?

-- Konrad
 
A

A. Sinan Unur

(e-mail address removed) (Konrad Eisele) wrote in
Assigning multiple hash with one statement is done with:
@a{'a','b'} = (1,2);

Assuming %a is a hash, that is referred to as, @a{'a','b'} is a hash
slice.
but how can I do it if I want to access the hash through
previous dereferences:
---------------------------

use strict;
use warnings;
use Data::Dumper;
@a = ({'a'=>1,'b'=>2});

@a now is an array containing a single element which is a reference to
an anonymous hash. BTW, you don't need to quote a and b above, that is
done automatically by using => for the keys you have chosen in this
case.
$b = \@a;

$b now contains a reference to \@a. (Incidentally, $b is a package
variable used by sort, so it is not a good idea to use it for other
purposes).
$b->[0]->{'a','b'} = (100,1000);

Well, $b->[0] is the reference to the hash you created above, so you
need to get a hash slice out of that first:

use strict;
use warnings;

my @x = ( { a => 1, b => 2 } );
my $y = \@x;

@{ %{$y->[0]} }{ qw(a b) } = (100, 1000);

use Data::Dumper;
print Dumper(\@x);

Sinan
 
T

Tad McClellan

Konrad Eisele said:
Assigning multiple hash with one statement is done with:
@a{'a','b'} = (1,2);


A "hash slice".

but how can I do it if I want to access the hash through
previous dereferences:
---------------------------
use Data::Dumper;
@a = ({'a'=>1,'b'=>2});
$b = \@a;
$b->[0]->{'a','b'} = (100,1000);
print Dumper(\@a);


You cannot force list context, but that doesn't matter because
your question is not related to context in any way.

Your real question is:

How do I dereference a hashref?

You can do that by applying "Use Rule 1" from

perldoc perlreftut


I like to do it in 3 steps.

Pretend you are slicing a plain-ol' hash:

@hash{'a','b'} = (100,1000);

Replace the _name_ with a block:

@{ }{'a','b'} = (100,1000);

Fill in the block with something that returns the right type of reference:

@{ $b->[0] }{'a','b'} = (100,1000);
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top