Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re^4: Split a column

by shabird (Sexton)
on Apr 13, 2020 at 17:45 UTC ( [id://11115481]=note: print w/replies, xml ) Need Help??


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

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?

Replies are listed 'Best First'.
Re^5: Split a column
by Fletch (Bishop) on Apr 13, 2020 at 18:03 UTC

    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.

Re^5: Split a column
by choroba (Cardinal) on Apr 13, 2020 at 18:00 UTC
    Because the hash contains each key just once.
    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
Re^5: Split a column
by AnomalousMonk (Archbishop) on Apr 13, 2020 at 18:44 UTC

    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:  <%-{-{-{-<

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11115481]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (3)
As of 2024-04-16 18:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found