2

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.
1
  • 3
    If you would use warnings, perl would warn you that nothing after the exec() would be executed. ("Statement unlikely to be reached at ...") Commented Jul 25, 2012 at 4:24

3 Answers 3

6

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".

Sign up to request clarification or add additional context in comments.

Comments

3

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");

Comments

0
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.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.