Perl Array Reference with hash reference - perl

my $var1=[{'a'=>'1','b'=>'2'},1];
print #$var1[0]->{a};
it will print 1
but, if i print like below:
print #$var1->{a};
it will print error like below
Can't use an undefined value as a HASH reference;
Can anyone explain diff between both print statement?

#$var1[0]->{a}
is usually written as
$var1->[0]{a}
The second syntax, though, is different.
#$var1->{a}
is equivalent to
#{$var1}->{a};
You can't dereference an array (#{$var1}) as a hash. Another question is why undef is reported, to which I don't know the answer.

In the first statement you print the value of key 'a' of the first element in your array (which is $var1)
In the second statement you print the value of key 'a' of your array (and get an error as array doesn't have keys)
Hope this helps

my $var1=[{'a'=>'1','b'=>'2'},1];
$var1 is array reference which contains hash reference at index 0 and scalar at index 1
to derefer $var1 to array, we have to use #$var1.(which gives the 2-element array)
And for accessing single element we have to use $$var1[0] or $var1->[0].
And again $var1->[0] is a hash reference.
To derefer it, we have to use $var1->[0]{'a'}.
But the statement "#$var1->{'a'}" is invalid, since
Hash reference is present at 0 index of the array "#$var1".
All references are scalar, Array cannot be used to derefer at hash reference.
For more information, please refer
Perl Data Structures Cookbook
Bless my Referents

Related

How to write two expressions as just one?

Can I write these two:
$var = tied $$var; # History=HASH(0x192a540)
$var->{ desc }; # object description info
By one expression:
${tied $$var}->{ desc };
I get the error:
Not a SCALAR reference at ...
The syntax SOMETHING->{key} tries to perform hash lookup in a reference SOMETHING. Here, your SOMETHING is ${...}, i.e. a scalar dereference.
Instead, you want
normal parentheses: (...)->{key}
hash access without an extra level of dereferencing: ${...}{key}.
The -> dereference operator is only optional between two subscripts. I.e. $foo{bar}[42] and $foo{bar}->[42] are equivalent and access a value from the %foo hash. But $foo->{bar}[42] is completely different: This accesses a value in the $foo hash reference.
The syntax %{SOMETHING}{key} is not correct because that dereferences SOMETHING as a hash, then access an entry. But the syntax for accessing an entry in a hash %SOMETHING is $SOMETHING{key}, not %SOMETHING{key}. The sigil % of a hash turns into a scalar sigil $ because you get a scalar entry out of the hash. This is known to be confusing, and has been fixed in Perl 6.

Perl: Meaning of double squared brackets after a string?

I don't understand a seemingly basic piece of code in Perl, which looks like this:
$line[$k][1]
What is the meaning of the double squared brackets?
I'm sorry if this was already asked or is so basic it can be found in every beginners book for Perl. I couldn't find it anywhere
It means you're working with a two dimensional array.
#!/usr/bin/env perl
use strict;
use warnings;
my #stuff = (
[ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
);
print $stuff[1][2];
#prints '7'
It means that what you have there is not "a string". It's an array called #line and that every element in #line is a reference to another array.
When you access a single element in a Perl array, the sigil changes from # (which implies multiple values) to $ (which implies a single value). So to look up the element with index $k in an array called #line, you use:
$line[$k]
But in your example, $line[$k] contains a reference to another array. To get from an array reference to one of the elements of the referenced array, we use the ->[...] syntax. So the second element of the array referenced by the $kth element of #line is given by:
$line[$k]->[1];
And in Perl, we have a rule that when two sets of array (or hash) look-up brackets are separated by just a dereferencing array, we can omit that arrow. So my previous example can be simplified to:
$line[$k][1];
A [..] is an array index. If you've got 2 of them, that means it's an array of arrays. In your example you're getting the 2nd element (indexes start at 0) of the $kth element of #line.
That you think it's a string is possibly a sign the code isn't very well written as there should be a line saying something along the lines of my #line;
Make sure the code has use strict; and use warnings; at the top and that should throw up any problems with the code.

how does this data structure work?

I have to some debugging on an existing script without having a lot of knowledge about perl.
This script uses data types like these to store all the fields from a file:
${$LineRefs->{FIELD_NAME}}
I've been trying to figure out how to find all possible fields separately by iterating over this scalar/hash/array or whatever it may be but I have no clue how.
Could anyone please point me in the right direction?
It's certainly very odd
$LineRefs is a reference to a hash which has an element with key FIELD_NAME whose value is a reference to a scalar
Like this
use v5.14;
my $LineRefs = {
FIELD_NAME => \99,
};
print ${ $LineRefs->{FIELD_NAME} }, "\n";
output
99
References to hashes and arrays are common because they allow a large data structure to be represented by a single scalar. But references to scalars are far less useful because they just replace a scalar by another scalar
I'm sorry, thanks #glennjackman I read the question too hastily and assumed it was about why a hash element was being dereferenced as a scalar
I've been trying to figure out how to find all possible fields separately by iterating over this scalar/hash/array or whatever it may be but I have no clue how
You're dealing with a hash, which is like an array but indexed by strings (keys) instead of integers (indexes)
You can use keys, values, or each to iterate over a hash
You can print all the keys and their values like this. Since your variable $LineRefs is a hash reference you need to dereference it as %$LineRefs
for my $key ( keys %$LineRefs ) {
my $value = $LineRefs->{$key};
print "$key => $value\n";
}
If your hash values really are references to scalars then you will see things like SCALAR(0x640448) printed for the values

Grabbing a list from a multi-dimensional hash in Perl

In Programming Perl (the book) I read that I can create a dictionary where the entries hold an array as follows:
$wife{"Jacob"} = ["Leah", "Rachel", "Bilhah", "Zilpah"];
Say that I want to grab the contents of $wife{"Jacob"} in a list. How can I do that?
If I try:
$key = "Jacob";
say $wife{$key};
I get:
ARRAY (0x56d5df8)
which makes me believe that I am getting a reference, and not the actual list.
See
perllol,
perldsc and
perlreftut
for information on using complex data structures and references.
Essentially, a hash can only have scalars as values, but references are scalars, Therefore, you are saving an arrayref inside the hash, and have to dereference it to an array.
To dereference a reference, use the #{...} syntax.
say #{$wife{Jacob}};
or
say "#{$wife{Jacob}}"; # print elements with spaces in between
I guess by this time you must be knowing that
$ refers to a scalar
and # refers to an array.
since you yourself said that the value for that key is an array,then you should
say #wife{$key};
instead of
say $wife{$key};

Are Perl subroutines call-by-reference or call-by-value?

I'm trying to figure out Perl subroutines and how they work.
From perlsub I understand that subroutines are call-by-reference and that an assignment (like my(#copy) = #_;) is needed to turn them into call-by-value.
In the following, I see that change is called-by-reference because "a" and "b" are changed into "x" and "y". But I'm confused about why the array isn't extended with an extra element "z"?
use strict;
use Data::Dumper;
my #a = ( "a" ,"b" );
change(#a);
print Dumper(\#a);
sub change
{
#_[0] = "x";
#_[1] = "y";
#_[2] = "z";
}
Output:
$VAR1 = [
'x',
'y'
];
In the following, I pass a hash instead of an array. Why isn't the key changed from "a" to "x"?
use strict;
use Data::Dumper;
my %a = ( "a" => "b" );
change(%a);
print Dumper(\%a);
sub change
{
#_[0] = "x";
#_[1] = "y";
}
Output:
$VAR1 = {
'a' => 'y'
};
I know the real solution is to pass the array or hash by reference using \#, but I'd like to understand the behaviour of these programs exactly.
Perl always passes by reference. It's just that sometimes the caller passes temporary scalars.
The first thing you have to realise is that the arguments of subs can be one and only one thing: a list of scalars.* One cannot pass arrays or hashes to them. Arrays and hashes are evaluated, returning a list of their content. That means that
f(#a)
is the same** as
f($a[0], $a[1], $a[2])
Perl passes by reference. Specifically, Perl aliases each of the arguments to the elements of #_. Modifying the elements #_ will change the scalars returned by $a[0], etc. and thus will modify the elements of #a.
The second thing of importance is that the key of an array or hash element determines where the element is stored in the structure. Otherwise, $a[4] and $h{k} would require looking at each element of the array or hash to find the desired value. This means that the keys aren't modifiable. Moving a value requires creating a new element with the new key and deleting the element at the old key.
As such, whenever you get the keys of an array or hash, you get a copy of the keys. Fresh scalars, so to speak.
Back to the question,
f(%h)
is the same** as
f(
my $k1 = "a", $h{a},
my $k2 = "b", $h{b},
my $k2 = "c", $h{c},
)
#_ is still aliased to the values returned by %h, but some of those are just temporary scalars used to hold a key. Changing those will have no lasting effect.
* — Some built-ins (e.g. grep) are more like flow control statements (e.g. while). They have their own parsing rules, and thus aren't limited to the conventional model of a sub.
** — Prototypes can affect how the argument list is evaluated, but it will still result in a list of scalars.
Perl's subroutines accept parameters as flat lists of scalars. An array passed as a parameter is for all practical purposes a flat list too. Even a hash is treated as a flat list of one key followed by one value, followed by one key, etc.
A flat list is not passed as a reference unless you do so explicitly. The fact that modifying $_[0] modifies $a[0] is because the elements of #_ become aliases for the elements passed as parameters. Modifying $_[0] is the same as modifying $a[0] in your example. But while this is approximately similar to the common notion of "pass by reference" as it applies to any programming language, this isn't specifically passing a Perl reference; Perl's references are different (and indeed "reference" is an overloaded term). An alias (in Perl) is a synonym for something, where as a reference is similar to a pointer to something.
As perlsyn states, if you assign to #_ as a whole, you break its alias status. Also note, if you try to modify $_[0], and $_[0] happens to be a literal instead of a variable, you'll get an error. On the other hand, modifying $_[0] does modify the caller's value if it is modifiable. So in example one, changing $_[0] and $_[1] propagates back to #a because each element of #_ is an alias for each element in #a.
Your second example is a little tricky. Hash keys are immutable. Perl doesn't provide a way to modify a hash key, aside from deleting it. That means that $_[0] is not modifiable. When you attempt to modify $_[0] Perl cannot comply with that request. It probably ought to throw a warning, but doesn't. You see, the flat list passed to it consists of unmodifiable-key followed by modifiable-value, etc. This is mostly a non-issue. I cannot think of any reason to modify individual elements of a hash in the way you're demonstrating; since hashes have no particular order you wouldn't have simple control over which elements in #_ propagate back to which values in %a.
As you pointed out, the proper protocol is to pass \#a or \%a, so that they can be referred to as $_[0]->{element} or $_[0]->[0]. Even though the notation is a little more complicated, it becomes second nature after awhile, and is much clearer (in my opinion) as to what is going on.
Be sure to have a look at the perlsub documentation. In particular:
Any arguments passed in show up in the array #_. Therefore, if you called a function with two arguments, those would be stored in $_[0] and $_[1]. The array #_ is a local array, but its elements are aliases for the actual scalar parameters. In particular, if an element $_[0] is updated, the corresponding argument is updated (or an error occurs if it is not updatable). If an argument is an array or hash element which did not exist when the function was called, that element is created only when (and if) it is modified or a reference to it is taken. (Some earlier versions of Perl created the element whether or not the element was assigned to.) Assigning to the whole array #_ removes that aliasing, and does not update any arguments.
(Note that use warnings is even more important than use strict.)
#_ itself isn't a reference to anything, it is an array (really, just a view of the stack, though if you do something like take a reference to it, it morphs into a real array) whose elements each are an alias to a passed parameter. And those passed parameters are the individual scalars passed; there is no concept of passing an array or hash (though you can pass a reference to one).
So shifts, splices, additional elements added, etc. to #_ don't affect anything passed, though they may change the index of or remove from the array one of the original aliases.
So where you call change(#a), this puts two aliases on the stack, one to $a[0] and one to $a[1]. change(%a) is more complicated; %a flattens out into an alternating list of keys and values, where the values are the actual hash values and modifying them modifies what's stored in the hash, but where the keys are merely copies, no longer associated with the hash.
Perl does not pass the array or hash itself by reference, it unfurls the entries (the array elements, or the hash keys and values) into a list and passes this list to the function. #_ then allows you to access the scalars as references.
This is roughly the same as writing:
#a = (1, 2, 3);
$b = \$a[2];
${$b} = 4;
#a now [1, 2, 4];
You'll note that in the first case you were not able to add an extra item to #a, all that happened was that you modified the members of #a that already existed. In the second case, the hash keys don't really exist in the hash as scalars, so these need to be created as copies in temporary scalars when the expanded list of the hash is created to be passed into the function. Modifying this temporary scalar will not modify the hash key, as it is not the hash key.
If you want to modify an array or hash in a function, you will need to pass a reference to the container:
change(\%foo);
sub change {
$_[0]->{a} = 1;
}
Firstly, you are confusing the # sigil as indicating an array. This is actually a list. When you call Change(#a) you are passing the list to the function, not an array object.
The case with the hash is slightly different. Perl evaluates your call into a list and passes the values as a list instead.