Hi,
I have one file name file.txt
It has the following contents:
#File Contents
StartTime,EndTime,COUNTER1,COUNTER2,COUNTER3
12:13,12:14,0,1,0
The output should be like this:
StartTime: 12:13
ENDTIME: 12:14
COUNTER1: 0
COUNTER2: 1
COUNTER3: 0
I have to create hash dynamically.
How can i create a hash dynamically and get the above output?
I tried in Google but could not get satisfactory result.
Regards
Vanitha
I don't know much about perl hashes (yet), but one could also solve that problem like this:
$ perl -lne '{@x=split(/,/,$_), $a=1 if /^Start/;
@y=split(/,/,$_) if $a == 1}
END{ for (0..4) {print "$x[$_]: $y[$_]"}}' file
StartTime: 12:13
EndTime: 12:14
COUNTER1: 0
COUNTER2: 1
COUNTER3: 0
$
pludi
3
Maybe not the most efficient algorithm, but for most applications it should do:
$ cat hash.pl
#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;
my $line;
my %hash;
$line = <DATA>;
chomp $line;
my @keys = split /,/, $line;
while ( $line = <DATA> ) {
chomp $line;
my @val = split /,/, $line;
for ( my $i = 0 ; $i <= $#val ; $i++ ) {
push @{ $hash{ $keys[$i] } }, $val[$i];
}
}
print Data::Dumper->Dump( [ \%hash ], [qw/hash/] );
__DATA__
StartTime,EndTime,COUNTER1,COUNTER2,COUNTER3
12:13,12:14,0,1,0
$
$
$
$ perl hash.pl
$hash = {
'COUNTER3' => [
'0'
],
'COUNTER1' => [
'0'
],
'COUNTER2' => [
'1'
],
'EndTime' => [
'12:14'
],
'StartTime' => [
'12:13'
]
};