capser
capser

Reputation: 2635

slicing and array into a hasn value

What I was trying to do was combine elements[1..3] into a single array, and then make the has out of that. Then sort by keys and print out the whole thing.

#!/usr/bin/perl
my %hash ; 
while ( <> ) {
    @elements = split /,/, $_;
    @slice_elements = @elements[1..3] ;
    if ($elements[0] ne '' ) {
        $hash{ $elements[0] } = $slice_elements[0];
    }
}

foreach $key (sort keys %hash ) {
       print "$key; $hash{$key}\n";
}

This is what I get when I print this out -

casper_mint@casper-mint-dell /tmp $ /tmp/dke /tmp/File1.csv


060001.926941; TOT
060002.029434; RTP
060002.029568; RTP
060002.126895; UL
060002.229327; RDS/A
060002.312512; EON
060002.429382; RTP
060002.585408; BCS
060002.629333; LYG
060002.712240; HBC

This is waht I want the elements of the array - element[0] is the key and element[1..3] in the value

060001.926941,TOT,86.26,86.48
060002.029434,RTP,310.0,310.66
060002.029568,RTP,310.0,310.74
060002.126895,UL,34.06,34.14
060002.229327,RDS/A,84.47,84.72
060002.312512,EON,56.88,57.04
060002.429382,RTP,310.08,310.77
060002.585408,BCS,58.96,59.06
060002.629333,LYG,46.13,46.41
060002.712240,HBC,93.06,93.23

Upvotes: 0

Views: 35

Answers (1)

Miller
Miller

Reputation: 35198

Always include use strict; and use warnings; at the top of EVERY perl script.

What you need is to create a new anonymous array [ ] as the value to your hash. Then join the values when displaying the results:

#!/usr/bin/perl
use strict;
use warnings;

my %hash;

while (<>) {
    chomp;
    my @elements = split /,/, $_;
    if ($elements[0] ne '' ) {
        $hash{ $elements[0] } = [@elements[1..3]];
    }
}

foreach my $key (sort keys %hash ) {
    print join(',', $key, @{$hash{$key}}) . "\n";
}

Of course, if your data really is fixed width like that, and you're not actually doing anything with the values, there actually is no need to split and join. The following would do the same thing:

use strict;
use warnings;

print sort <>;

Upvotes: 2

Related Questions