Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Re: how to use perl variable in system command to run on unix

by Laurent_R (Canon)
on Sep 03, 2013 at 22:47 UTC ( #1052190=note: print w/replies, xml ) Need Help??

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 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"; . .. [... many files omitted] + DB<4> foreach $file ( @list_files) {print $file, "\n" if 50 > -M "Ol +d_PL_programs/$file;"}; # prints files younger than 50 days

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/ Old_PL_programs/ Old_PL_programs/

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/*.*");

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/*.*");

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1052190]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (9)
As of 2018-06-24 15:37 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.