Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Creating an array from a text file

by mikevanhoff (Acolyte)
on Aug 13, 2002 at 15:38 UTC ( [id://189830]=perlquestion: print w/replies, xml ) Need Help??

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

I would like to create an array from a text file that uses each element from the array to perform some action. I have the actions working, but I have to either enter the next item manually or create copies. My idea is to create a seperate text file with all of the items, then read the file into an array etc. I need help with the array creation and how to place the current code.

Replies are listed 'Best First'.
Re: Creating an array from a text file
by Ovid (Cardinal) on Aug 13, 2002 at 15:53 UTC

    We're going to need some more information about this. Populating an array from a text file is easy:

    open FILE, "< $somefile" or die "Cannot open $somefile for reading: $! +"; chomp( my @file_data = <FILE> ); close FILE or die $!;

    At this point, @file_data will contain the individual lines of the file (assuming you haven't changed the $/ variable). Is the above enough for you, or do you have more questions? Showing us your code might help, too.

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

Re: Creating an array from a text file
by Abigail-II (Bishop) on Aug 13, 2002 at 15:51 UTC
    my @array = do {local @ARGV = "yourfile"; <>};
    Abigail

      Okay, I have to ask: was that just tongue-in-cheek, or do you see some benefit to potentially confusing the poor seeker? :)

      Cheers,
      Ovid

      Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

        Reading in a file into an array is a pretty basic thing to do in Perl. In fact, if you don't know this standard idiom, you shouldn't be programming - you should be studying. So, if my solution causes the seeker to fetch the manuals ago, all the better. If he doesn't and all he wants is something delivered on a silver platter, then I don't want to spend more than one line in giving an answer - and I didn't while my answer was correct and not inefficient.

        And besides, it's an idiom I sometimes use myself. It's faster to code than the open/read/close lines.

        Abigail

Re: Creating an array from a text file
by aufrank (Pilgrim) on Aug 13, 2002 at 15:59 UTC

    mikevanhoff--

    Greetings and welcome to the Monastery! Your first node may very well be an interesting question, but it's hard to tell because it is a bit vague. Statements like "[use] each element of the array to perform some action" are hard for readers to respond to because they don't give enough details about exactly what you're trying to do. One way to help your fellow monks help you is to post code along with your question. You say that you have the actions working-- if we could see that code it would greatly help us to understand the nature of your question.

    That said, there are a few things that might help you. The first is reading some of the docs available at this site (use the search box), at http://www.perldoc.com, or included with your local perl distribution (type perldoc perldoc for meta help. look into the -f and -q options, specifically).

    It seems like what you're looking for is very easily accomplished. perldoc -f open would be a good place to learn how to access a file. As for getting the contents of a file into an array, consider this block of code:

    sub words_from_file { my $file_path = shift; my @word_list; open WORD_FILE, "< $file_path" or die "Could not open $file_path: $!\n"; @word_list = map { split /,\s*|\n/ } <WORD_FILE>; close WORD_FILE or die "Could not close $file_path: $!\n"; return \@word_list; }

    You might also want to read the node that inspired that code, which can be found here. Also, if you are trying to perform some operation on every element of the array once you have created it, you should definitely get comfortable with map-- one of the most useful tools in perl, IMO :) Check out this excellent tutorial by jeffa for help with map.

    If you have any questions about what that code is doing, please feel free to respond and I'll be more than happy to explain.

    good luck!
    --au

    UPDATE: I should have explained that this code will make each separate word an element of the array-- to use whole lines rather than individual words, definitely use the far simpler code in Ovid's response. If you do go line by line, be sure to check out chomp. I also added a close statement to my code, 'cause it should have been there in the first place.

      Well, heck, if we're going to go down the road of confusing the person, we can make each individual line an array ref of elements split on predetermined separators :)

      #!/usr/bin/perl -w use strict; use Data::Dumper; $_ = [ grep {$_} split /[\s,:]/ ] for my @data = <DATA>; print Dumper \@data; __DATA__ foo bar, baz this that: those

      Note: that was tongue-in-cheek, but I can see that point that Abigail-II made.

      Cheers,
      Ovid

      Join the Perlmonks Setiathome Group or just click on the the link and check out our stats.

      aufrank and all responders; Thank you for the explaination and suggestions on asking questions. All of these responses will be of some help, even the oneliner. Although I understand the concepts of opening and reading from file, understanding how the array is created, and actually substuting the elements into my code is vague to me. I have included my code so that my question is more explicit. I am trying to delete the files in the reports directory that are x days old. I have 67 directories under /opt/web that all have reports directories. I would like to place all of these paths into a text file to be read into the array, and have the following actions performed.
      # open the directory for reading chdir "/opt/web/hr83tst/reports"; opendir(REP, "/opt/web/hr83tst/reports") || die "Cannot open the dire +ctory /opt/web/hr83/reports $! "; open(remlog,">/Scripts/dir-removed.log"); # open a file to keep as a +log of directories removed. print remlog "Directories removed this date : ",`date`, "\n"; # list the contents of the directory. These should be directories. while ($name = readdir(REP)) { if (-M $name >= 10) { print "$name\n" unless($name eq "images"); print remlog "$name\n" unless($name eq "images"); `rm -r $name` unless($name eq "images"); # THIS WILL REMOVE THE D +IRECTORY AND ALL OF ITS subdirectories and Files. } } close remlog; closedir(REP)
        You can also use the File::Find module as follows to populate your array:
        use File::Find; find sub { push @reportdirs, $File::Find::name, if -d && /^reports$/ } +, "/opt/web";
        That way, you won't have to modify your file every time your directory structure changes. You then can readdir each directory in the array to begin processing the files it contains.
        Jason
Re: Creating an array from a text file
by Zaxo (Archbishop) on Aug 13, 2002 at 16:07 UTC

    What kind of action do you have in mind, and what is the format of the file? If you have one shell command per line, why not run it in the shell? I'll assume that's not the case. To read a file into an array is elementary:

    open FOO, '<', '/path/to/bar.data' or die $!; my @actions = <FOO>; close FOO or die $!;

    I'll suppose the actions are keys to a "dispatch table", a hash of coderefs, followed by some arguments, space delimited. Call the hash %action_code.

    for (@actions) { my @act = split " "; $action_code{$act[0]}->(@act[1..$#act]); }

    If &$action_code{foo} returns a value, you may prefer map to what I have shown.

    You made this easy, but maybe pointless, by leaving out all the details.

    After Compline,
    Zaxo

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (2)
As of 2024-04-20 06:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found