user1126849
user1126849

Reputation: 291

Retrieving array from array of arrays?

use strict;
my @a;
my @b = ();
@a = (3, 4);

push @b, [@a];

my @c = @b[0];
print @c;

How do I properly retrieve @c? It tells me Scalar value @b[0] better written as $b[0].

(This isn't my real code for privacy reasons, but in the real code I have something like this:

my @a = @{$b[$i]};
print @a;

This says "Use of uninitialized value," but still prints what it's supposed to.

Upvotes: 0

Views: 97

Answers (2)

drquicksilver
drquicksilver

Reputation: 1635

If you have an array reference stored in $b[0] - which is your situation - then you retrieve it as

$ref = $b[0]    # I just want it as a reference

or

@arr = @{$b[0]} # I want it as a (new) array

or

$elt = $b[0][1] # I want to directly access the second element
$elt = $b[0]->[1] # alternative syntax, same thing.

Upvotes: 3

Vorsprung
Vorsprung

Reputation: 34297

For details on the syntax for array access see perldata

@c[0] is a single element array slice(!) $c[0] is correct

$c[0]->[0] is "3" and $c[0]->[1] is "4"

For more details on arrays of arrays see perldsc and perllol

Upvotes: 2

Related Questions