http://www.perlmonks.org?node_id=1052190


in reply to how to use perl variable in system command to run on unix

I would suggest that you use Perl, rather than system commands in Perl. Especially, calling awk from Perl is a kind of disgrace, since Perl can do internally everything that awk can do, and much more, better, with finer controls and often faster (nothing against awk, which I am still using quite regularly, but much less than before I started Perl). I don't have time now to write an equivalent script in Perl, but just an example on how to get a similar result shown here as 3 simple commands under the Perl debugger:

$ perl -de 42 Loading DB routines from perl5db.pl version 1.33 Editor support available. Enter h or `h h' for help, or `man perldebug' for more help. main::(-e:1): 42 DB<1> opendir $dirh, "Old_PL_programs" or die "could not open dir $! +"; DB<2> @list_files = readdir $dirh; DB<3> print " @list_files"; . .. 24.pl 2tab.pl aa.pl ack_nomem.pl [... many files omitted] VAR.pl + walk_HoA.pl whitespace.pl xml.pl zip_read.pl DB<4> foreach $file ( @list_files) {print $file, "\n" if 50 > -M "Ol +d_PL_programs/$file;"}; # prints files younger than 50 days ack_nomem.pl fringe.pl khalou2.pl

Undoubtedly, piped Unix commands can be very powerful and are tempting, but you are starting Perl, you should try to do things in perl, and you will learn that most of that command piping could be done in Perl. For example, my above example under the debugger could be stripped down to one single line of code:

DB<6> print join "\n", grep { -M $_ < 50 } glob ("Old_PL_programs/*. +*"); Old_PL_programs/ack_nomem.pl Old_PL_programs/fringe.pl Old_PL_programs/khalou2.pl

Or, if I want to remove the path from the filename:

DB<7> print join "\n", map {s/^.*\/(.+)/$1/r} grep -M $_<50, glob (" +Old_PL_programs/*.*"); ack_nomem.pl fringe.pl khalou2.pl

The last command above would have to be slightly changed on versions of Perl prior to 5.14.

Update: the last command above could be better written with no dependancy on the Perl version as follows (not tested):

  DB<7> print map {s/^.*\/(.+)/$1/; "$_\n"} grep -M $_<50, glob ("Old_PL_programs/*.*");