Be careful what you ask for -- you may just wind up getting it. Are you really sure you want the exact output of the dir command, or do you just want the names of the files, or the date and/or the size as well. That is, do you expect to have to parse the output downstream to do something else with it?

If this is the case, you are better off doing to internally in Perl, thereby saving the time it takes to launch off the sub-process as well as the time it takes to parse the results.

For instance, if you want to gather the names of the files and their respective sizes, you could do something like:

#! /usr/bin/perl -w use strict; my $dir = shift || '.'; opendir D, $dir or die "Cannot open dir $dir: $!\n"; my %size; while( defined( my $file = readdir(D) )) { # only makes sense to ask for the size of a file next unless -f $file; $size{$file} = (stat $file)[7]; } closedir D;

And there you have it. If you want to save different information, look at the stat function stat. If you need to recurse directories (i.e. emulate dir's -s switch), take a look at File::Find. If you need to store more than one thing (e.g. the date and the size) then it would be a good time to learn about references (perldoc perlreftut and perldoc perlref).


--
g r i n d e r

In reply to Re: Getting the output of a shell command by grinder
in thread Getting the output of a shell command by ellem

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.