opmeitle
opmeitle

Reputation: 195

Perl system + split + array

my name is luis, live in arg. i have a problem, which can not solve.

**IN BASH**
pwd
/home/labs-perl
ls
file1.pl file2.pl

**IN PERL**
my $ls = exec("ls");
my @lsarray = split(/\s+/, $ls);
print "$lsarray[1]\n"; #how this, i need the solution. >> file.pl
file1.pl file2.pl # but this is see in shell.

Upvotes: 2

Views: 1557

Answers (3)

ysth
ysth

Reputation: 98398

print <*> // die("No file found\n"), "\n";

(Though using an iterator in scalar context should usually be avoided if the script will be doing anything further.)

Upvotes: 0

perreal
perreal

Reputation: 97948

The output you see is not from the print statement, it is the console output of ls. To get the ls output into a variable, use backticks:

my $ls = `ls`;
my @lsarray = split(/\s+/, $ls);
print "$lsarray[1]\n";

This is because exec does not return, the statements after it are not executed. From perldoc:

The exec function executes a system command and never returns; use system instead of exec if you want it to return. It fails and returns false only if the command does not exist and it is executed directly instead of via your system's command shell

But using system command will not help you as it does not allow output capturing, hence, the backticks. However, using glob functions is better:

my @arr = glob("*");
print $arr[1], "\n";

Also, perl array indices start at 0, not 1. To get file1.pl you should use print "$lsarray[0]\n".

Upvotes: 6

Borodin
Borodin

Reputation: 126722

It is bad practice to use the shell when you can write something within Perl.

This program displays what I think you want.

chdir '/home/labs-perl' or die $!;
my @dir = glob '*';
print "@dir\n";

Edit

I have just understood better what you need from perreal's post.

To display the first file in the current working directory, just write

print((glob '*')[0], "\n");

Upvotes: 3

Related Questions