Wednesday, 15 June 2011

perl - assning the first column of the file to hash key and the rest to hash value -



perl - assning the first column of the file to hash key and the rest to hash value -

i have file follows:

23 line number 23 2 line number 2 87 line number 87 28 line number 28 4 line number 4 83 line number 83

i need take first column hash keys , sec hash value. should sort file using hash keys

this easy: split line @ whitespace 2 pieces. first part $key, rest $value.

we sort keys of %hash alphabetically, , print out data.

#!/usr/bin/perl utilize strict; utilize warnings; %hash; while (<>) { chomp; # remove newline ($key, $value) = split ' ', $_, 2; $hash{$key} = $value; } # or shorter: # %hash = map {chomp; split ' ', $_, 2} <>; @sorted_keys = sort keys %hash; $key (@sorted_keys) { print "$key $hash{$key}\n"; } # or shorter: # print "$_ $hash{$_}\n" sort keys %hash;

the input can provided via stdin or file named in command line argument.

output input provided:

2 line number 2 23 line number 23 28 line number 28 4 line number 4 83 line number 83 87 line number 87

if want numerical sorting, alter sort keys sort {$a <=> $b} keys.

perl

No comments:

Post a Comment