Trouble executing piped shell commands in perl code

I am trying to execute a piped combination of shell commands inside a perl program.
However, it is not working as desired.

This is my program, i am trying to print only filenames from the output of ls -l

$ cat list_test
#!/usr/bin/perl -w
use strict;
my $count=0;
my @list=`ls -l|awk '{print $9}'`;
print "@list";

it produces output as

$ ./list_test
Use of uninitialized value in concatenation (.) or string at ./list_test line 5.
total 104
 -rwxr-xr-x 1 sam ugroup  59 Mar 28 08:13 ch2_p1
 -rwxr-xr-x 1 sam ugroup 127 Mar 28 08:18 ch2_p2
 -rwxr-xr-x 1 sam ugroup 202 Mar 28 08:21 ch2_p3
 -rwxr-xr-x 1 sam ugroup 175 Mar 28 08:28 ch2_p4
 -rwxr-xr-x 1 sam ugroup 170 Mar 28 09:52 ch2_p5
 -rwxr-xr-x 1 sam ugroup  86 Apr 10 09:20 ch3_p1
 -rwxr-xr-x 1 sam ugroup 193 Apr 10 09:34 ch3_p2
 -rwxr-xr-x 1 sam ugroup 232 Apr 10 10:16 ch3_p3
 -rwxr-xr-x 1 sam ugroup 334 Apr 17 03:16 ch4_p1
 -rwxr-xr-x 1 sam ugroup 142 Apr 17 03:20 ch4_p2
 -rwxr-xr-x 1 sam ugroup 418 Apr 17 03:34 ch4_p3
 -rwxr-xr-x 1 sam ugroup  38 Apr 18 02:29 ch5_p1
 -rwxr-xr-x 1 sam ugroup 180 Apr 18 02:49 ch5_p2
 -rwxr-xr-x 1 sam ugroup 259 Apr 18 02:53 ch5_p3
 -rwxr-xr-x 1 sam ugroup 308 Apr 20 00:46 ch6_p1
 -rwxr-xr-x 1 sam ugroup 261 Apr 20 00:56 ch6_p2
 -rwxr-xr-x 1 sam ugroup 220 Apr 20 01:17 ch6_p3
 -rwxr-xr-x 1 sam ugroup  77 Apr 20 03:35 ch7_p1
 -rwxr-xr-x 1 sam ugroup  81 Apr 20 03:36 ch7_p2
 -rwxr-xr-x 1 sam ugroup  75 Apr 20 03:36 ch7_p3
 -rwxr-xr-x 1 sam ugroup  84 Apr 20 04:42 ch7_p4
 -rwxr-xr-x 1 sam ugroup  82 Apr 20 04:42 ch7_p5
 -rwxr-xr-x 1 sam ugroup  92 Apr 20 04:45 ch7_p6
 -rw-rw-rw- 1 sam ugroup 218 Apr 20 04:46 ch7_sample1
 -rwxr-xr-x 1 sam ugroup  82 Apr 23 05:33 list.pl
 -rwxr-xr-x 1 sam ugroup 155 Apr 24 08:52 list_test

however, when i execute those commands on command line it executes perfectly(this is how the output should be of the perl code)

$ ls -l | awk '{print $9}'
ch2_p1
ch2_p2
ch2_p3
ch2_p4
ch2_p5
ch3_p1
ch3_p2
ch3_p3
ch4_p1
ch4_p2
ch4_p3
ch5_p1
ch5_p2
ch5_p3
ch6_p1
ch6_p2
ch6_p3
ch7_p1
ch7_p2
ch7_p3
ch7_p4
ch7_p5
ch7_p6
ch7_sample1
list.pl
list_test

please help!

Use -1 switch of ls instead of awk

 
#!/usr/bin/perl -w
use strict;
my $count=0;
my @list=`ls -1`;
print "@list";

1 Like

That worked thanks,
but can you explain why awk didn't work inside the code

Just like shell, perl also uses the positional parameters $1,$2 etc. So, when you are using $9 in the awk command syntax, perl interprets $9 as one of the other variables in the perl script. Hence the error.

If you still want to use awk command, escape the $ sign like below:

 
#!/usr/bin/perl
use strict;
my $count=0;
my @list=`ls -l|awk '{print \$9}'`;
print "@list";

If your perl code is nothing but a thin membrane atop 90% shell scripting, it might be time to learn shell, as well. I used to write enormous perl scripts before realizing, if I removed the perl, I'd be left with something simpler and more functional.