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

Re: Extract the number of the species for txt file

by choroba (Cardinal)
on Apr 27, 2016 at 14:46 UTC ( [id://1161637]=note: print w/replies, xml ) Need Help??


in reply to Extract the number of the species for txt file

Extract the counts to a hash:
#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; my %counts; while (<>) { my @species = split; my @numbers = split ' ', <>; warn "Different number of columns at line $.!" if @species != @num +bers; for my $i (0 .. $#species) { push @{ $counts{ $species[$i] } }, $numbers[$i]; } } for my $spec (keys %counts) { say $spec; for my $count (@{ $counts{$spec} }) { say $count; } }

($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

Replies are listed 'Best First'.
Re^2: Extract the number of the species for txt file
by fan li (Initiate) on May 05, 2016 at 08:49 UTC
    Hi choroba

    Thanks for your help. Your code works fine and can out put the all species and corresponding numbers to the screen. However, I just want to extract one specific specie and corresponding number at a time. Meanwhile, the corresponding number should be 0 if there is no such specific specie.And it would be better if the outcome can write into a new text file instead of the screen. Take O4 as an example, there should be just one output and should be like this

    O4

    0 # There is no “O4” specie in (1), so the corresponding number is 0.

    3

    0 # There is no “O4” species in (5), so the number is 0 too.

    It will be grateful if you can help me.

    Fan Li

      If you know the species in advance, there's no need to remember the counts for the remaining ones.
      #!/usr/bin/perl use warnings; use strict; use feature qw{ say }; say my $search_for_species = 'O4'; while (<>) { my %counts; my @species = split; my @numbers = split ' ', <>; warn "Different number of columns at line $.!" if @species != @num +bers; for my $i (0 .. $#species) { $counts{ $species[$i] } = $numbers[$i]; } say $counts{$search_for_species} // 0; }

      To output to a file, use redirection:

      perl script_from_choroba.pl > new_file

      ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others exploiting the Monastery: (6)
As of 2024-04-19 14:32 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found