Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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.

e.g.:
#!/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"; }

In reply to Re: Put "ls" in array by serf
in thread Put "ls" in array by PatricF

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others sharing their wisdom with the Monastery: (7)
As of 2024-04-16 17:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found