Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Put "ls" in array

by PatricF (Initiate)
on Apr 26, 2012 at 09:25 UTC ( #967278=perlquestion: print w/replies, xml ) Need Help??
PatricF has asked for the wisdom of the Perl Monks concerning the following question:

Hi, I'm totally new to Perl and I'm making a script and need some help. I'm on Linux and I want to put the output of "ls" into an array. How do I do this? I need to be able to do something like this:
print @array[2]
And it will output the third file/directory if you know what I mean.

Replies are listed 'Best First'.
Re: Put "ls" in array
by jethro (Monsignor) on Apr 26, 2012 at 09:36 UTC

    You can get the output of system commands like ls into an array with this:

    my @array= `ls`;

    Note that these are backticks, not the normal quotes. Also you might use chomp() afterwards on the array to remove the line endings

    In your case it would also be possible to use opendir()/readdir() to read a directory like a file

    The order of the files on disk will look pretty random to you by the way (at least if you have deleted and created lots of files in this directory already, otherwise they might be in order of creation). If you want to sort them, perl has a sort() function as well

      It's totally depends on your requirment. If you simply want to push into array and list then here is snippet..

      my @dir= `ls`; print "\n @dir"; output: #test# allcases bin codebase core execute_dir nonqa precutoff reversal stamp1 stamp2
Re: Put "ls" in array
by pelagic (Priest) on Apr 26, 2012 at 09:30 UTC
Re: Put "ls" in array
by serf (Chaplain) on Apr 26, 2012 at 09:57 UTC

    The answer really depends on whether you're trying to learn about populating arrays and are using the output of ls as an example, or trying to list files in a directory and get those into your program.

    If the main aim is to get the list of files into your program, I'd recommend pelagic's answer. The opendir documentation has boilerplate code that you can copy into your program and modify to suit your needs. It's normally better in terms of efficiency, powerfulness and control over what's going on to do things like this internally in Perl (which is what opendir does) where you can, rather than running an external shell command to get the same data and then parsing its text output.

    If you're learning about arrays, then the backticks & the glob work, as would using an open which allows you to process the output of the command on the way into your array.

    #!/usr/bin/perl # # # use warnings; use strict; my @files; open (my $ls_fh, "/bin/ls|") || die "Can't run '/bin/ls': $!\n"; while (defined (my $line = <$ls_fh>)) { # next if $line =~ /pattern_I_want_to_ignore/; chomp $line; push @files, $line; } close $ls_fh; print "Third file: $files[2]\n"; for my $file ( @files ) { print "$file\n"; }
      What a bunch of lines! If I wanted to ignore some pattern, why not:
      my @files = grep {!/pattern_I_want_to_ignore/} `ls`;
      Or for the grasshoppers who haven't realized yet that Perl started its life as a glue language, and never deviated from that, and hence get the rashes as soon as they see a call to an external program:
      use autodie; opendir my $dir, "."; my @files = grep {!/pattern_I_want_to_ignore/} sort grep {!/^\./} # simulate ls readdir $dir;
Re: Put "ls" in array
by hperange (Beadle) on Apr 26, 2012 at 09:44 UTC
    Hello, You could do so via the glob operator.
    #!/usr/bin/perl use strict; use warnings; my @list = glob(".* *"); print $_, "\n" for (@list);
Re: Put "ls" in array
by DrHyde (Prior) on Apr 26, 2012 at 10:06 UTC
    What have you tried so far, what do you think it should have done, and how does what it actually did differ from what you expected?
Re: Put "ls" in array
by xiaoyafeng (Chaplain) on Apr 27, 2012 at 15:13 UTC
    for a beginner, I recommend File::Find::Rule for this usage. below is some examples grasp from its synopsis:
    # find all the subdirectories of a given directory my @subdirs = File::Find::Rule->directory->in( $directory ); # find all the .pm files in @INC my @files = File::Find::Rule->file() ->name( '*.pm' ) ->in( @INC );

    I am trying to improve my English skills, if you see a mistake please feel free to reply or /msg me a correction

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://967278]
Front-paged by Corion
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (5)
As of 2017-05-28 17:34 GMT
Find Nodes?
    Voting Booth?