in reply to Reading from text file
Hello sarath92,
Welcome to the Monastery. Although fellow Monks have already answered your question, I wanted to add something minor. I believe you are a bit of a beginner so maybe a more analytical step by step script could help you understand how to do something similar in future for your self.
Sample of code:
#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %hash; while (<>) { # read files from command line (separate by space) e.g. i +n.txt sample.txt etc... next if /^(\s*(#.*)?)?$/; # skip blank lines and comments chomp; # lines that are not skipped remove new line character '\n' my @tmp = split /:/; # split line on column ':' if (exists $hash{$tmp[0]}) { # check if key exists in hash $hash{$tmp[0]} .= ":".$tmp[2]; # if exists append } else { $hash{$tmp[0]} = $tmp[2]; # if not exists create new element with +data } } continue { close ARGV if eof; } print Dumper \%hash; open(my $fh, '>', 'out.txt') # open file to print data or die "Could not open file 'out.txt' $!"; while( my( $key, $value ) = each %hash ){ # iterate over the hash print $fh $key.':'.$value . "\n"; # write data to file } close $fh # close file after finishing or warn "Could not close file 'out.txt' $!"; __END__ $ perl test.pl in.txt $VAR1 = { 'Thailand' => '6', 'China' => '2:2:70', 'Japan' => '6:10' }; $ cat out.txt Thailand:6 China:2:2:70 Japan:6:10
Hope this helps, BR.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Reading from text file
by Marshall (Canon) on Mar 23, 2018 at 16:49 UTC |