I searched in Google, but I did not find anything useful in it.
Even though there are many tutorials for Perl, I did not find any tutorial which would mention a hash which has different values for each and every key?
Is such a thing possible in Perl?
For example, can there be a hash like which has 2 keys (a, b) where:
$myhash{"a"}=1;
$myhash{"b"}=[ 'hamnet', 'shakespeare', 'robyn', ];
Is the above possible?
I tried this:
#!/usr/bin/perl
use strict;
my %x;
$x{"a"}="b";
$x{"b"}=['c','d'];
foreach (keys %x)
{
print $_."\n";
print "$x{$_}";
}
but it is outputting:
a
bb
ARRAY(0x1ece50)
I am confused about how to access the elements of this hash.
I would like to tell you all that, even though I know Perl a bit, I am a complete novice regarding hashes.
OK, I found one thing — to access the array inside the hash, I need to do:
@{$x{"b"}}
But as I have told you, the value of a hash can be either an array or a scalar value, so for accessing the above hash, I need to initially identify the type of the value and then access it! How can I do this?
That is, how can I identify whether a value for a key is either a scalar, an array or a hash?
You might’ve tried looking at the tutorials included in your Perl distribution, which include the Perl Data Structures Cookbook (perldsc). It includes a chapter on “More Elaborate Records”, which gives examples on how to create and used a hash whose values have different types.
Since you seem to be a unfamiliar with the use of references and the
refoperator, you may also want to take a look at Mark’s very short tutorial about references (perlreftut).Note that all of these tutorials (and many more) already come with your Perl distribution, and you can access them by typing e.g.
on the command line.
(On some systems, you may need to install an extra package to enable the
perldoccommand. This is highly recommended if you intend to do any Perl programming at all.)