in reply to hash values

I thinking that a couple of changes are needed (untested).
#!/usr/bin/perl -w use strict; # for some value of $infile1 open (IN, "$infile1") or die "can't open $infile1"; my $linecount = 0; $hash{$line} = $linecount++ while (<IN>); close IN;

Replies are listed 'Best First'.
Re^2: To assign values to a Hash
by graff (Chancellor) on Feb 08, 2008 at 09:16 UTC
    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);