[pm-h] populate an array from data in a text file

G. Wade Johnson gwadej at anomaly.org
Mon Apr 21 05:17:26 PDT 2008


Hi Russell,

On Sun, 20 Apr 2008 21:24:19 -0500
"Russell L. Harris" <rlharris at oplink.net> wrote:

> I am trying to read data from a text file into an array, the goal
> being to copy various elements from the array.  From chapter 2 (pages
> 66-67) of the third edition of "Programming Perl", it appears to me
> that the text file is termed a "here-document".

A here document is just a form of multi-line string. I don't believe it
is what you need here.

> Because of the need to read a file, I suspect that I should be using
> the diamond operator, but I haven't been able to figure out how it
> would fit into this script.

I can think of a couple of ways that I normally do this:

my @phonetic = ();
while(<>) # read each line into $_
{
   chomp;  # Remove newline from $_
   push @phonetic, $_; # add the line to @phonetic
}

or

chomp( my @phonetic = <> ); # all in one

Both of these will read each line in all of the files listed on the
command line of the script into the array.

If you are not passing the file on the command line (or resetting
@ARGV), you will need to use the diamond operator with a file handle.
Add the following line before the above:

open( my $fh, '<', 'words' ) or die "Unable to open 'words': $!";

Then replace '<>' with '<$fh>' in either the reading code above. Using
the second example:

open( my $fh, '<', 'words' ) or die "Unable to open 'words': $!";
chomp( my @phonetic = <$fh> );
close( $fh );

Hope that helps.

> 
> Here is my Perl script:
> 
> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
> 
> #!/usr/bin/perl
> 
> @ARGV = qw# words #; # read the here-document
> 
> @phonetic = <<EOF =~ m/^\s*.+/gm;
> EOF

I'm not really sure what you are intending to do with the regular
expression. The first example I gave above is easier to modify to
discard some lines. You just add

   next unless m/^\s$.+/;

before the line with the push.

> 
> print $phonetic[0];
> print $phonetic[1];
> print $phonetic[2];
> print $phonetic[3];
> print $phonetic[4];
> print $phonetic[5];
> 
> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
> 
> 
> Here is the content of my here-document, which is a text file named
> "words":
> 
> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
> 
> able
> baker
> charlie
> delta
> echo
> foxtrot
> EOF
> 
> %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
> _______________________________________________
> Houston mailing list
> Houston at pm.org
> http://mail.pm.org/mailman/listinfo/houston
> Website: http://houston.pm.org/


-- 
Never express yourself more clearly than you think.    -- Niels Bohr


More information about the Houston mailing list