1

I have a strange issue with Perl and dereferencing.

I have an INI file with array values, under two different sections e.g.

[Common]
animals =<<EOT
dog
cat
EOT

[ACME]
animals =<<EOT
cayote
bird
EOT

I have a sub routine to read the INI file into an %INI hash and cope with multi-line entries.

I then use an $org variable to determine whether we use the common array or a specific organisation array.

@array = @{$INI{$org}->{animals}} || @{$INI{Common}->{animals}};

The 'Common' array works fine, i.e. if $org is anything but 'ACME' I get the values (dog cat) but if $org equals 'ACME'` I get a value of 2 back?

Any ideas??

1 Answer 1

6

Derefencing arrays is of course not forcing scalar context. But using || is. Therefore things like $val = $special_val || "the default"; work just fine while your example doesn't.

Therefore @array will contain either a single number (the number of elements in the first array) or, if that is 0, the elements of the second array.

The perlop perldoc page even lists this example speficially:

In particular, this means that you shouldn't use this for selecting
between two aggregates for assignment:

    @a = @b || @c;              # this is wrong
    @a = scalar(@b) || @c;      # really meant this
    @a = @b ? @b : @c;          # this works fine, though

Depending on what you want, the solution could be:

my @array = @{$INI{$org}->{animals}}
   ? @{$INI{$org}->{animals}}
   : @{$INI{Common}->{animals}};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, spot on, don't how I coped before I found this site :) .

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.