1

Given a HoHoA

my %FIELDS = (
    LA => {
      NAME => [1],
      ADDRESS => [2,3,4,5],
      TYPE => [6],
      LICENCE => [0],
      ACTIVE => [],
    },
...
);

I'm trying to make a copy of a particular array

my @ADDRESS_FIELDS = @{$FIELDS{$STATE}->{ADDRESS} };

Since everything inside %FIELDS is by reference the arrow de-references the inner hash and the @{} de-references the array. (I understand that the arrow isn't strictly necessary)

print $ADDRESS_FIELDS[3]."\n";
print @ADDRESS_FIELDS."\n";

gives

5
4

The first print behaves as expected but the second one is giving me the scalar value of, I assume, the referenced array instead of a new copy. Where am I going astray?

2
  • 1
    What do you mean by "instead of a new copy"? The 4 is indeed just the array evaluated in scalar context, which yields the number of elements. Maybe you were looking for print "@ADDRESS_FIELDS\n"? Commented Jan 15, 2016 at 14:56
  • Headdesk Sometimes we overlook the little things. Thanks. Commented Jan 15, 2016 at 15:01

3 Answers 3

4

The concatenation operator forces scalar context on its operands. Use a comma instead:

print @array, "\n";

Note that the elements are separated by $,, which is empty by default.

Or, to separate the array elements by $" (space by default) in the output, use

print "@array\n";

Or, join them yourself:

print join(' ', @array), "\n";
Sign up to request clarification or add additional context in comments.

Comments

1
cat my.pl 
#!/bin/perl
#
use strict;
use warnings;
use Data::Dumper;

my %FIELDS = (
    LA => {
        NAME => [1],
        ADDRESS => [2,3,4,5],
        TYPE => [6],
        LICENCE => [0],
        ACTIVE => []
    },
);

my @addy = @{$FIELDS{LA}->{ADDRESS}};
foreach my $i(@addy){
    print "i=$i\n";
}
perl my.pl
i=2
i=3
i=4
i=5

1 Comment

you forgot to reference LA
0
print @ADDRESS_FIELDS."\n";

Evaluates your array in a scalar context and returns the number of elements (which in your case is 4).

print join(', ', @ADDRESS_FIELDS)."\n";

is what you want i guess.

HTH

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.