Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Greetings! What would be the best way to read the contents of a file into an array with a format like this:
name
name
name
name...
I've tried
while (<FILE>) { @names = <FILE>; }
but it lops off the first entry and puts spaces around the names. Any assistance would be greatly appreciated.

Title edit by tye

Replies are listed 'Best First'.
Re: Novice
by Zaxo (Archbishop) on Dec 01, 2002 at 05:15 UTC

    You're mixing two usages.

    while (<$handle>) { ... } is used to read a file one record at a time and interpose programming instructions, usually based on content.

    @foo = <$handle>; slurps a file, from current position to end, into an array of raw records, including the record seperator, $/, at the end of each except maybe the last.

    Use the first if there is little context to preserve between records, the second if there is more complicated parsing to be done.

    After Compline,
    Zaxo

Re: Novice
by rir (Vicar) on Dec 01, 2002 at 04:57 UTC
    You probably want:
    my @names = <FILE>; chomp @names;
    The while loop is not needed.
Re: Reading file contents into an array
by CountZero (Bishop) on Dec 01, 2002 at 10:46 UTC
    If you use <FILE> in an array context, you slurp the entire file into the array in one move. You do not need a while-loop around it. Effectively, the first line/name gets read by the while (<FILE>), saved into $_ and never used.

    I'm not sure how the spaces around the names come about. It might have something to do with the way your file is built: are there any spaces following the names and before the EOL character(s)?

    CountZero

    "If you have four groups working on a compiler, you'll get a 4-pass compiler." - Conway's Law

Re: Novice
by pg (Canon) on Dec 01, 2002 at 04:57 UTC
    In your code, there are two things you need to be aware of:
    • The newline-char's are still there. If you do not want them, use chomp to remove them.
    • You may have blank lines at the end of your files. If you do not want them, use grep to get rid of them.
Re: Reading file contents into an array
by jjdraco (Scribe) on Dec 01, 2002 at 23:00 UTC
    Don't forget my favorite way to read text files Tie::File.
    use Tie::File; my @file; tie @file, 'Tie::File, 'path/to/file';


    jjdraco
    learning Perl one statement at a time.