FaceBro
FaceBro

Reputation: 859

How to understand this in perl

my @skipper = qw(blue_shirt hat jacket preserver sunscreen);
my @skipper_with_name = ('The Skipper' => \@skipper);

How to understand the second line?

print @skipper_with_name;

got the following msg:

The SkipperARRAY(0x209cf90)

Upvotes: 2

Views: 97

Answers (3)

matt freake
matt freake

Reputation: 5090

As Stevenl mentions, Data::Dumper only prints out the structure of array or hash, if you pass a reference into it, not the structure itself. Otherwise it prints what the structure is (ARRAY) and its memory address.

Also, if you are expecting @skipper_with_name to be a HASH and not an ARRAY, I will point out that @ is only used for arrays, % is the symbol for a HASH (so it would be %skipper_with_name). Also, although => is most commonly used in hashes to show the key/value relationship, it is essentially just a comma, so can be used without error to create an array.

my @skipper_with_name = ('The Skipper' => \@skipper);

is the same as:

my @skipper_with_name = ('The Skipper',  \@skipper);

you can see here:

 $skipper_with_name[0] = 'The Skipper' 
 $skipper_with_name[1] = \@skipper

Upvotes: 2

Christoph
Christoph

Reputation: 51261

It's a new Array which has a reference (the slash in front of the array \) to your initial array stored in it. If you print it, you only get the memory address, you need to dereference it first by again prepending the @ symbol to get the content of the hash.

However this makes no real sense, Arrays can only have numeric indixes. What you probably want to do is to use a hash.

my %skipper_with_name = ('The Skipper' => \@skipper);

now you can reference to the array via the 'The Skipper' identifier.

print Dumper $skipper_with_name{'The Skipper'};
#or
print @{ $skipper_with_name{'The Skipper'} };

Upvotes: 1

stevenl
stevenl

Reputation: 6798

The backslash in front of @skipper gets the reference to the array.

You can see the actual structure if you:

use Data::Dumper;
print Dumper \@skipper_with_name;

Perhaps you wanted a hash instead for the second array, which means that The Skipper can be used as a key for accessing @skipper:

my %skipper_with_name = ('The Skipper' => \@skipper);
print Dumper \%skipper_with_name;
my @skipper_copy = @{$skipper_with_name{'The Skipper'}};

Note how I've used @{...} to dereference the array reference.

Upvotes: 3

Related Questions