I have an array and tried to convert the array contents to a hash with keys and values. Index 0 is a key, index 1 is a value, index 2 is a key, index 3 is a value, etc.
But it is not producing the expected result. The code is below:
open (FILE, "message.xml") || die "Cannot open\n";
$var = <FILE>;
while ($var ne "")
{
chomp ($var);
@temp = split (/[\s\t]\s*/,$var);
push(@array,@temp);
$var = <FILE>;
}
$i = 0;
$num = @array;
while ($i < $num)
{
if (($array[$i] =~ /^\w+/i) || ($array[$i] =~ /\d+/))
{
# print "Matched\n";
# print "\t$array[$i]\n";
push (@new, $array[$i]);
}
$i ++;
}
print "@new\n";
use Tie::IxHash;
tie %hash, "Tie::IxHash";
%hash = map {split ' ', $_, 2} @new;
while ((my $k, my $v) = each %hash)
{
print "\t $k => $v\n";
}
The output produced is not correct:
name Protocol_discriminator attribute Mandatory type nibble value 7 min 0 max F name Security_header attribute Mandatory type nibble value 778 min 0X00 max 9940486857
name => Security_header
attribute => Mandatory
type => nibble
value => 778
min => 0X00
max => 9940486857
In the output you can see that the hash is formed only with one part, and another part of the array is not getting created in the hash.
Can anyone help?
To append a new value to the array of values associated with a particular key, use push : push @{ $hash{"a key"} }, $value; The classic application of these data structures is inverting a hash that has many keys with the same associated value. When inverted, you end up with a hash that has many values for the same key.
The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.
Hash variables are preceded by a percent (%) sign. To refer to a single element of a hash, you will use the hash variable name preceded by a "$" sign and followed by the "key" associated with the value in curly brackets..
To assign some values to the array, just enclose them in parentheses. You can retrieve them with the index number. Notice how the @ changed to a $ for the print statement; I wanted it to return a scalar, a single thing, not a list of things. If you want to do things to the whole array, use the @ .
Nothing more to it than:
%hash = @array;
On a related note, to convert all elements of @array
into keys of %hash
. Some people ending up here might really want this instead...
This allows use of exists function:
my %hash;
$hash{$_}++ for (@array);
my %hash = map { $_ => 1 } @array
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With