Amit Saxena wrote:
Hi all,

Hello,

I am trying to make a perl code which would read a matrix (basically an
array which contains references to other arrays) and initialize a hash with
the first value of each dereferenced array acting as a key and remaining
elements as values using references.

The source code and output are mentioned below :-

Source Code
-----------------

[root]# cat k1.pl
#! /usr/bin/perl

use strict;
use warnings;

my @arr =       (
                        [1, 2, 3, "a", "b"],
                        [4, 5, 6, "c", "d"],
                        [7, 8, 9, "e", "f"]
                );
my @arr1;
my %h;
my $a;
my $key1;
my $i;
my $n;

You should only declare your variables in the smallest scope possible, that is the root cause of your problem.


print "Matrix is as follows :- \n";
foreach $a (@arr)

You shouldn't really use $a or $b outside of a sort code block.

foreach my $item ( @arr )


{
        print "Row = @{$a}\n";

        @arr1 = "";

Why are you assigning "" to $arr1[ 0 ]?


        $n = @{$a};

        for ($i=1; $i<=$n-1;$i++)

That is usually written as:

          for my $i ( 1 .. $#$a )


        {
                $arr1[$i-1] = ${$a}[$i];
        }

Or more simply (without the loop):

          @arr1 = @{ $a }[ 1 .. $#$a ];


        $h{ ${$a}[0] } = [EMAIL PROTECTED];

Because @arr1 is declared at file scope the reference you are assigning is always the same so every value of %h points to the same array.

You need to either declare @arr1 inside this loop to get a new reference each time through the loop:

          my @arr1 = @{ $a }[ 1 .. $#$a ];
          $h{ ${$a}[0] } = [EMAIL PROTECTED];

or copy the list to an anonymous array:

          $h{ ${$a}[0] } = [ @{ $a }[ 1 .. $#$a ] ];


}

print "Hash is as follows :- \n";
foreach $key1 (keys %h)

foreach my $key1 ( keys %h )

{
        print "Key -> [$key1] : Value -> [EMAIL PROTECTED]";
}

print "\n";




John
--
Perl isn't a toolbox, but a small machine shop where you
can special-order certain sorts of tools at low cost and
in short order.                            -- Larry Wall

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to