tags:

views:

26

answers:

1

Hi,

I have an array and i try to convert the array contents to a hash with keys and values (index 0 is key, index 1 is value, index 2 is key, index 3 is value, etc).

But some how i was struck and it is not producing the expected result. code is given 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. O/P is given below,

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 O/P u can see hash is formed only with one part and another part of array is not at all getting created in the hash.

Can anyone help.

Thanks Senthil kumar.

A: 

Try:

my %h = {};

while ($#arr > 0) {
    my $key = shift @arr;
    $h[$key] = shift @arr;
}

This will put @arr, an array as specified, into %h, a hash, such that the even items of @arr (from 0) are keys and the odd items are values.

I honestly don't even know what you were trying to do with most of that code above.

A tip: always use strict when you're learning Perl. It'll help stop a lot of subtle bugs.

Borealid
hi, i have code like this %h = {};while ($#new > 0){ $key = shift @new; $h[$key] = shift @new;}while ((my $k, my $v) = each %h){ print "\t $k => $v\n";}I am getting output as , HASH(0x9e1ef20) =>I dont know where i went wrong can u pls help it out
Senthil kumar