Print the name of files in the directory using Perl

Hi All,
I am stuck with a problem and i want your help, what i want to do is

I have a directory name dircome
and there are 6 files present in this directory, the name of the files are d1,d2,d3,d4,d5,d6.

The Perl script print the files name, means the output should be
d1
d2
d3
d4
d5
d6

Try like...

ls -l *.*| awk -F ' ' '{print $9}'

Use the function system.

#! perl
system("ls <path to directory>");

Thanks,
Kalai

Above command not working.. Please help me.

Hi,
Try this one,

#! /usr/bin/perl
use strict;
my $mDir="/home/cf/ranga1";
opendir(DIR1,"$mDir") or die "unable to open dir $mDir";
my @mRes=grep{/^[^.]/} readdir(DIR1);
closedir(DIR1);
sort(@mRes);
print "@mRes\n";

Cheers,
Ranga:-)

A one-liner using only Perl (unlike the others presented so far):

perl -e 'print join "\n",grep { -f } <*>'

Explanation:

  • <*> is a glob that expands to all entries in the current directory
  • grep is a function that works pretty much like the shell utility. It expects a statement block returning true or false values on the parameters.
  • The -f is a shorthand for testing if a parameter (here it's the anonymous automatic variable $_ ) is a regular file or not
  • And finally it all gets nicely formatted by join and print ed

If you are running a Perl script there is no need to spawn a shell to do this, Perl has a number of ways (as always) of doing this, you can use a glob to get the values

print join("\n",glob("$dir_name/*")),"\n";

Or you could open the directory and read the contents.

opendir(my $directory,"$dir_name"); 
print join("\n", grep {! /^\./} sort(readdir $directory));
closedir($directory);

The glob is obviously easier to use, however if you need to do more complex processing than just printing the filenames the opendir, readdir , closedir approach gives you more flexibility.

Hi the above query give result as
.
..
d1
d2
d3
d4
d5
d6

But the expected output i want is
d1
d2
d3
d4
d5
d6

Hi,

I have updated in my previous post. Please check it.

Cheers,
Ranga:)

$ perl -e '@files=<*>;@sorted = sort @files; print join("\n",@sorted)'