Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Populating an array

by Anonymous Monk
on Mar 28, 2001 at 01:50 UTC ( #67649=perlquestion: print w/replies, xml ) Need Help??

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

I am a total newby!
How would I go about populating an array from a flat file.
I have a file like this
eggsalad pickles eggs salad dressing sandwich bread meat tomato
I would like to put
eggsalad pickles eggs salad dressing

as a value in the array and
sandwich bread meat tomato
As another value. The problem is that I am to new to do this on my own. The actual file is hundreds of entries long with each entry separated by a whitespace line.There are other things that I need to do to each array ,but I think I can do the rest myself.Can someone please help me. Thank You

Replies are listed 'Best First'.
Re: Populating an array
by Adam (Vicar) on Mar 28, 2001 at 02:12 UTC
    What do you already know? Do you expect us to write the script for you? Why should we?

    How to read from a file (The cmd-line way):
    prompt> perl -we '@filecontents =<>' filename

    How to read from a file (The script way):

    #!/usr/bin/perl -w use strict; open FILEHANDLE, "< filename" or die "Failed to open 'filename', $!"; my @contents = <FILEHANDLE>; close FILEHANDLE;
    How to read from a file (The OO way):
    #!/usr/bin/perl -w use strict; use IO::File; my $file = IO::File->new( "< filename" ) or die "Failed to open 'filename', $!"; my @contents = <$file>; $file->close();
    So you see, your question is not straight forward. The answer that I would give is:
    #!/usr/bin/perl -w use strict; use IO::File; use constant FILENAME => filename; my $file = IO::File->new( "< ". FILENAME ) or die "Failed to open '@{[FILENAME ]}', $!"; my @elements; { local $/ = $/.$/; @elements = <$file>; } $file->close();
    With the hopes that my way contains so many perlisms that if your question is for HW that your teacher will recognize the plagarism, and that if you are truly trying to learn, then you will have plenty to figure out while perusing the library.
      When our student friend turns in his assignment he should be sure to add single quotes around filename on line number 4.

      He should also add comments explaining what is going on and add some code to print out the array values. A final result (containing the obfuscatory dereferenced reference) is thus:

      #!/usr/bin/perl -w use strict; use IO::File; use constant FILENAME => 'filename'; #Replace filename with name of in +put file. my $file = IO::File->new( "< ". FILENAME ) or die "Failed to open '@{[FILENAME ]}', $!"; # Dereferenced array + ref and OS error my @elements; { local $/ = $/.$/; #Replace default input delimeter (\n) with (\n\n +) @elements = <$file>; } $file->close(); #Now test to see that everything reads out okay print "Here are the elements of the array:\n"; for (my $i = 0; $i < @elements; $i++) { print "Element number $i of the array is:\n$elements[$i]\n"; }
      If our friend makes some effort to understand what he has submitted then he will have learned his lesson well. Maybe we will see him here with Tye and Merlyn someday.
        Good catch on the quotes around the filename. I intentionally left it all uncommented. But lets have some more fun with it:
        #!/usr/bin/perl -w use strict; use IO::File; use constant FILENAME => 'filename'; { package cntr; sub TIESCALAR{bless[pop],__PACKAGE__} sub FETCH{ $_[0][0]++ } } my $file = IO::File->new( "< ". FILENAME ) or die "Failed to open '@{[FILENAME]}', $!"; my @elements; { local ( $a, $/ ) = $/.$/; @elements = split $a => <$file>; } $file->close(); print "Here are the elements of the array:\n"; tie my $i, 'cntr', 1; print map {$i.': {'."$_}$/"} @elements;
        Yeah, that would go over well with a teacher or professor.

        Update: So I changed the code a little from the original post. I actually tested it, and didn't like the way the newlines hung around. This fixes that. View source for the old code.

Re: Populating an array
by c-era (Curate) on Mar 28, 2001 at 01:57 UTC
    Set the input record separator to two newlines:
    $/ = "\n\n"; # Sets the input record separator to two newlines my @array = <FILE>; # Put the file in an array $/ = "\n"; # Sets the input record separator to one newline (the defau +lt)
Re: Populating an array
by boo_radley (Parson) on Mar 28, 2001 at 01:53 UTC
Re: Populating an array
by mr.nick (Chaplain) on Mar 28, 2001 at 02:22 UTC
    Here is a suggestion for you: use a hash of arrays to store your information. You can key the hash off the main recipe name ('sandwich', 'eggsalad') easily enough:
    #!/usr/bin/perl use strict; my $file='mydata.txt'; my %hash; open IN,$file || die $!; my $key; while (<IN>) { ## remove the end-o-line chomp; ## blank line means a new recipe if (/^\s*$/) { undef $key; next; } ## stuff the key with something if (! defined $key) { $key=$_; next; } ## okay, split the line and add the parts push @{$hash{$key}},split /\s{2,}/,$_; } close IN; for my $key (sort keys %hash) { print "'$key' is made with: ".join(",",@{$hash{$key}})."\n"; }
    Now, the only problem with this is that the ingredients have to be seperated with more than one space (as with your example).
Re: Populating an array
by jeroenes (Priest) on Mar 28, 2001 at 02:43 UTC
    Here comes another shameless plug: you can use this. With
    $a = supersplit('/[\s\n]+/','\n\n',"/my/flat/file/");
    You'll end up with a 2D array. See perlref how to cope with that.

    Jeroen
    "We are not alone"(FZ)

Re: Populating an array
by strredwolf (Chaplain) on Mar 28, 2001 at 02:29 UTC
    Use a hash and enter it all into a state engine. The code is left for the student.

    --
    $Stalag99{"URL"}="http://stalag99.keenspace.com";

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://67649]
Approved by root
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (5)
As of 2020-08-07 12:43 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which rocket would you take to Mars?










    Results (45 votes). Check out past polls.

    Notices?