I'm thinking you may have misunderstood the OP. For each distinct full-line text pattern in the file, the desired hash value is "the number of lines" -- i.e. how many times the given text pattern occurs as a line in the file. (See the following reply from poolpi.)

Apart from that, there are problems with your suggested code. It looks like your idea is for the hash value to be the line number in the file where a given text pattern is last seen, but you are post-incrementing $linecount when assigning it to each hash element (so the first line of the file is line number 0 instead of 1), and it won't work anyway, because you use "$line" as the hash key without ever assigning anything to $line -- in fact, if you tried "perl -cw" on your script as originally posted, it won't compile because $line is never declared.

(Lot's of monks post untested code and that's fine, but as a rule, when posting any snippet that includes "use strict;", you should at least pass it through "perl -cw" first to see whether it compiles.)

Update: by the way, to implement your idea (store the last line number containing a given text pattern), you don't need any variables other than the hash (and maybe the file name, but probably not even that):

#!/usr/bin/perl use strict; my %hash; $hash{$_} = $. while (<>); print "$hash{$_} : $_" for (sort {$hash{$a}<=>$hash{$b}} keys %hash);

In reply to Re^2: To assign values to a Hash by graff
in thread hash values by Abhisek

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.