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.
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".
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With