in reply to hashes of arrays

{ local $/; foreach (@file) { open(FILE,"$_"); $hash{$_}{file_contents} = <FILE>; close(FILE) } }
that sets line separator to undef, and slurps in whole file instead of one line.
                - Ant

Replies are listed 'Best First'.
Re: Re: hashes of arrays
by Tortue (Scribe) on Apr 03, 2001 at 23:37 UTC
    Another solution, since you said you wanted an array, is to read the file in array context, without changing the input line separator :
    @{$hash{$_}{file_contents}} = <FILE>;
    -- the array guy
Re: Re: hashes of arrays
by jeroenes (Priest) on Apr 04, 2001 at 00:10 UTC
    Two tiny nitbits:
    1. It's a good thing to put the local in a block (so ++), but with unexperienced users (the poster) it may be nice to note what it does. Well, the {local....} BLOCK restricts the scope of local to that block. So after the block, the $/ has it's original value (the line separator). One can read more about these and other vars in perlvar.
    2. (Really tiny)The foreach was copied from the original post (and it works), but here is a for more precise. A foreach loop is used to change the contents of an array, for is not. So for reading in a file, I would recommend for. A typical use for foreach:
      @array = 0..100; foreach $item (@array){ $item += 10 if $item <100; } print join "\n", @array; #prints the numbers 10 to 109 and 100
      You can read more about it in for vs foreach.
    Hope this helps,

    Jeroen
    "We are not alone"(FZ)
    Update: For clarity, for and foreach *are* synonyms. It's just a matter of convention....

      I tried the following:
      #!/usr/local/bin/perl use strict; my @array = ('one', 'two', 'three'); for my $element (@array) { $element = uc($element); } for my $element (@array) { print "$element\n"; } exit;
      The output was:
      ONE
      TWO
      THREE

      In this regard the for does in fact seem to be synonymous with foreach. In the extent that the elements of the array are changed both function the same.

      But I must admit that by programming habit and for the sake of readiblity I adhere to the convention:

      foreach loop to change the contents of an array
      "for" when I'm not.

      In spite of my habits and preferences apparently they both work the same. But alas my C background has me using for when I'm just stepping through array indexes.

Re: Re: hashes of arrays
by mbond (Beadle) on Apr 03, 2001 at 23:27 UTC
    woo.

    Thanks... I'd like it emphasize that making it local to a block is a good thing ... for some reason i didn't bother when i tested it real quick ... ;-)

    feel free to beat me for my stupidity.

    Mbond.