Reputation: 79
I am reviewing a script and I have come across a block that I can't figure out:
if ((@ifAliasVals[1])&&(%{@ifAliasVals[0]})) {
...
}
What is the %{@ifAliasVals[0]}
doing?
Upvotes: 1
Views: 73
Reputation: 17936
The syntax %{ ... }
treats the expression between the braces as a hash-reference, and dereferences it, giving you the entire hash.
The syntax @ifAliasVals[0]
returns an array slice from the array @ifAliasVals
. In this case, the array slice only has one element, and so that would have been better written as $ifAliasVals[0]
. In any case, it gives you the first element of the array @ifAliasVals
.
The entire expression %{ @ifAliasVals[0] }
therefore interprets the first element of @ifAliasVals
as a hash reference, dereferencing it, yielding the contents of that hash.
In the context of your if-statement above, the right-hand of the &&
will be true if the hash has any elements, and will be false if the hash is empty.
Upvotes: 2
Reputation: 385847
if (@ifAliasVals[1] && %{ @ifAliasVals[0] })
is a bad way of writing
if ($ifAliasVals[1] && %{ $ifAliasVals[0] })
%{ EXPR }
is a hash dereference. %{ EXPR }
is basically the same as %hash
, but accesses the via a reference rather than its name.
In scalar context, %hash
returns true iff the hash has any elements, so %{ $ifAliasVals[0] }
checks if the hash referenced by $ifAliasVals[0]
has elements.
my $hash1_ref = { };
my $hash2_ref = { a => 1 };
say %{ $hash1_ref } ? 'has elements' : 'empty'; # empty
say %{ $hash2_ref } ? 'has elements' : 'empty'; # has elements
Upvotes: 4