>I am supposed to write a function where I could pass the directory name
That sounds awfully like homework to me but I'll give you the benefit of the doubt.
Here's a solution that fits into your requirements
but I would caution that
japhy's solution above of using
readdir is
much better than your proposed solution of using backticks to run ls. Anyway, here it is.
On my system, an ls -l produces something like this. It could be different on your system!:
-rwxr-xr-x 1 rhettbull Domain U 294 Aug 31 10:59 dirs.pl
drwxr-xr-x 2 rhettbull Domain U 0 Aug 31 10:58 testdir
It's obvious that the directory entries start with a "d" as the first character on the line. So, we parse the lines looking for a "d" at the beginning of the line. Then we parse those lines with split. Notice that I limit split to 10 columns because the directory name might have spaces in it. I call split in list context and only grab the 10th entry (the directory name) since you didn't ask for the other stuff. Note that this will miss symlinks and I caution once again to use readdir.
#!/bin/perl
use strict;
use warnings;
my $lookhere = shift || '.';
parse_dir($lookhere);
sub parse_dir
{
my $rootdir = shift || '.';
my @listing = `ls -l $rootdir`;
foreach (@listing)
{
chomp;
if (/^d/)
{
my $dir = (split /\s+/, $_, 10)[9];
print "$dir\n";
}
}
}
Originally posted as a Categorized Answer.
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.