I have a strange issue with Perl and dereferencing.
I have an INI file with array values, under two different sections eg
[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, ie 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??
Derefencing arrays is of course not forcing scalar context. But using ||
is. Therefore things like $val = $special_val || "the default";
$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}};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.