in reply to CSV file reading and comparison

I made a ramshackle code, quick fix kindoff, will optimize it later, it works good! the only problem is the order, I want the order of the keys while printing to be the same as when the keys were read in! In this case it seems to be sorted by name. Any tips please!
$goldcsv = @ARGV[0]; #$newcsv = @ARGV[1]; my %goldhash; my @keyarray; open GOLD, "$goldcsv"; my $i = 0; while (<GOLD>) { chomp; $i=$i+1; if ($i eq 1) { @temparray = split (",",$_); my $j=0; foreach $elem (@temparray) { $j= $j+1; next if ($j eq 1); push (@keyarray, $elem); } next; } @temparray = split(",",$_); $testcasename = @temparray[0]; foreach my $value (1..$#temparray) { $goldhash{$testcasename}{$keyarray[$value-1]} = $temparray[$va +lue]; } } for $testcase (keys %goldhash) { print "$testcase: "; for $value (keys %{ $goldhash{$testcase} }) { print "$value = $goldhash{$testcase}{$value} "; } print "\n"; }

Replies are listed 'Best First'.
Re^2: CSV file reading and comparison
by toolic (Bishop) on Feb 27, 2008 at 14:06 UTC
    I want the order of the keys while printing to be the same as when the keys were read in!
    Tie::IxHash will do this for you.
    Any tips please!
    Yes, I have some more tips...

    Use the strictures to find other potential problems with your code:

    use warnings; use strict;

    This would produce the following warnings:

    Scalar value @ARGV[0] better written as $ARGV[0] at ... Scalar value @temparray[0] better written as $temparray[0] at ...
    It will then be necessary to declare all variables with my to get the code to compile again.

    Always check success when you open a file, and always close the file.

    I refactored your code:

    #!/usr/bin/env perl use warnings; use strict; use Tie::IxHash; tie my %goldhash, "Tie::IxHash"; my $goldcsv = shift; my @keyarray; my @temparray; open my $GOLD_FH, '<', $goldcsv or die "Can not open $goldcsv $!\n"; my $i = 0; while (<$GOLD_FH>) { chomp; $i++; if ($i eq 1) { @temparray = split /,/; my $j=0; for my $elem (@temparray) { $j++; next if ($j eq 1); push @keyarray, $elem; } next; } @temparray = split /,/; my $testcasename = $temparray[0]; for my $value (1 .. $#temparray) { $goldhash{$testcasename}{$keyarray[$value-1]} = $temparray[$va +lue]; } } close $GOLD_FH or die "Can not close $goldcsv $!\n"; for my $testcase (keys %goldhash) { print "$testcase: "; for my $value (keys %{ $goldhash{$testcase} }) { print "$value = $goldhash{$testcase}{$value} "; } print "\n"; }

    Here is the output. Is this what you had in mind?

    Test1: Stage1Mem = 44 Stage2Time = 45 Stage2Mem = 43 Stage1Time = +45 Test2: Stage1Mem = 7 Stage2Time = 34 Stage2Mem = 45 Stage1Time = 2 +334
      I was actually going to incorporate strict and warnings, this was just a quick hashup. I also liked the suggestion of using persdc, its a good document. I am really new with complex data structures, and thanks for all the help rendered.