I wanted to make a quick, stupid, snippet (AWTDI) that would read a filehandle into a hash, where the keys were the numbers of the line in the file. The following is what I came up with, does anyone else have any dumb ways to do this? :) Just a note, a did this quickly (while I was waiting on hold for a con-call). I padded the value of $.-- with a 0 simply for output reasons.
open(FH,"test") || die "You suck because $!"; my %hash = map {sprintf("%02d",$.--),$_} reverse <FH>; close FH; print qq{$_ => $hash{$_}\n} for sort keys %hash;

Replies are listed 'Best First'.
Re: Reading file into a numbered hash
by Fastolfe (Vicar) on Nov 23, 2000 at 00:29 UTC
    What's the advantage of using a hash with keys being the line numbers over using an array?
    @array = <FILE>; # reads each line of FILE into an $array[$element] print "Line 10 of FILE: $array[9]\n";
    Each line is individually addressable as-is. Hashes don't buy us any efficiency (in fact, it's quite a bit less efficient).
      I thought I mentioned I was looking for AWTDI. On a personal note, I enjoy hashes over arrays. I find it more intuitive to say $hash{10} to get the tenth line, than $array[9]. I also like being able to 'delete $hash{10}' and actually have my hash have 1 less key. And, I would have to benchmark this, but since I was just looking for AWTDI, I don't care enough to, but depending on the size of the file, the hash lookups should be faster.

      PS: Before someone says that you can delete an array element.. yes, you can. But all it does it put that element back to an uninitialized state, it doesn't really delete the element. If you have an array with 10 elements, and you delete one, you still have 10 elements.

      Cheers,
      KM

        I only offered that because if you're dealing with a largish amount of data, it's significantly more efficient to deal with a sequential data structure (such as an array) than a "random-access" one with a sequential key.