Array in a hash question?

J

Jamie Smyth

I have a hash defined as,

my %data = (
'wn_l' => $wn_l, 'wn_u' => $wn_u, 'wn_d' => $wn_d,
'npts' => $#spc+1, 'spc' => [@spc], 'label' => $label,
);

and I would like to extract the data in the @spc array. I tried,

my @spc = %data{'spc'};

and

my $spc = %data{'spc'};

but this results in the array being created directly in @spc[0]. I
ended up using:

my $d = $data{'spc'};
my @data = ();
push @data, @$d;

which gives me a 1dimensional array @data that I can use... the
problem is that I don't really know why this works and it looks a
little weird. Can someone explain?

Thanks.
 
M

Matt Garrish

Jamie Smyth said:
I have a hash defined as,

my %data = (
'wn_l' => $wn_l, 'wn_u' => $wn_u, 'wn_d' => $wn_d,
'npts' => $#spc+1, 'spc' => [@spc], 'label' => $label,
);

and I would like to extract the data in the @spc array. I tried,

my @spc = %data{'spc'};

The value for key spc is a reference to an array (hash values are always
scalars). In order to access the array, you need to dereference the
reference:

my @array = @{ $data{'spc'} };

Matt
 
T

Tad McClellan

Jamie Smyth said:
I have a hash defined as,

my %data = (
'wn_l' => $wn_l, 'wn_u' => $wn_u, 'wn_d' => $wn_d,
'npts' => $#spc+1, 'spc' => [@spc], 'label' => $label,
);

and I would like to extract the data in the @spc array.


Apply "Use Rule 1" from:

perldoc perlreftut


1) pretend is is a plain array

my @spc = @data;

2) replace the _name_ with a block ...

my @spc = @{ };

3) ... that returns a reference to an array

my @spc = @{ $data{spc} };
 
J

John W. Krahn

Matt said:
Jamie Smyth said:
I have a hash defined as,

my %data = (
'wn_l' => $wn_l, 'wn_u' => $wn_u, 'wn_d' => $wn_d,
'npts' => $#spc+1, 'spc' => [@spc], 'label' => $label,
);

and I would like to extract the data in the @spc array. I tried,

my @spc = %data{'spc'};

The value for key spc is a reference to an array (hash values are always
scalars). In order to access the array, you need to dereference the
reference:

my @array = @{ $data{'spc'} };

Also, the 'npts' entry isn't required as the array in scalar context
will return the number of elements:

my $npts = @{ $data{ spc } };


John
 

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,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top