You have a great start on your script! As for your 'struggles': 1) yes, and ++ is a perfectly appropriate and a common construct; 2) The value for what? If you mean incrementing the hash value, you're doing it correctly. If you mean $row[18] to get the value of col 19, you're doing it correctly.; and 3) no.

Here are some suggested changes to consider for your script:

use strict; use warnings; my $filename = $ARGV[0]; my %gene_count; open my $fh, '<', $filename or die "Cannot open $filename: $!"; while ( my $line = <$fh> ) { chomp; my @row = split( "\t", $line ); $gene_count{ $row[18] }++ if $row[18]; } close($fh); print "$_ => $gene_count{$_}\n" for sort keys %gene_count;

Since you're sending your script the filename from the command line, you can let Perl handle the file i/o. If you split on ' ' (whitespace) you don't need to chomp. Also, you can send split a LIMIT to its splitting, so it's not splitting all columns. Using this LIMIT can significantly speed the splitting process. Given this, the following is functionally equivalent:

use strict; use warnings; my %gene_count; while (<>) { my @rows = split ' ', $_, 20; $gene_count{ $row[18] }++ if $row[18]; } print "$_ => $gene_count{$_}\n" for sort keys %gene_count;

Your original script's logic is good; only minor fixes were needed. You've done well...

Hope this helps!


In reply to Re: Looping through a file, reading each line, and adding keys/editing values of a hash by Kenosis
in thread Looping through a file, reading each line, and adding keys/editing values of a hash by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.