in reply to Re^2: Split a column
in thread ead a file which has three columns and store the content in a hash

Hashes in Perl are unordered. You can use Hash::Ordered instead. See also the module's documentation for other options and their comparison.

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^4: Split a column
by shabird (Sexton) on Apr 13, 2020 at 17:45 UTC

    Now i am counting the values in the third column i.e how many up words how many down words and how many NA. For that i wrote the following program:

    @values = values(%hash); for $element (@values){ if ($element =~ /up/){ $sumA++; }if(($element =~ /down/)){ $sumB++ }if(($element =~ /NA/)){ $sumC++ } } print "Number of up is: $sumA\n"; print "Number of down is: $sumB\n"; print "Number of NA is: $sumC\n";
    it is doing a great job but when i add a same row in the last of the file it doesn't count its up, down or NA word. why is that?

      Presuming you mean that you're adding a row which duplicates the key and value from another row you're not going to change your hash. If you've seen a key "foo" with a value "up", setting $hash{ "foo" } = "up" again doesn't really change anything in %hash. Hashes are unordered and maintain a single value for each key slot. If you need the count of rows with a particular value then count them as you read things.

      my %counts_per_value; [... inside your while loop ...] $hash{ $first } = $third; $counts_per_value{ $third }++; [...] for my $value ( sort keys %counts_per_value ) { say qq{$value => $counts_per_value{ $value }; }

      The cake is a lie.
      The cake is a lie.
      The cake is a lie.

      Because the hash contains each key just once.
      map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

      You seem to misunderstand or lack understanding of the behavior of hashes, or associative arrays to use their formal name. Please see the discussions of keys, values and each in the Perl documentation.


      Give a man a fish:  <%-{-{-{-<