Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re^3: cd in perl not working?

by Bethany (Scribe)
on Aug 13, 2014 at 03:53 UTC ( [id://1097213]=note: print w/replies, xml ) Need Help??


in reply to Re^2: cd in perl not working?
in thread cd in perl not working?

Old thread, yes. But you got me thinking too. In the spirit of TMTOWTDI I offer an alternative: Put the commands in one system() call, separated by semicolons. Works for me using Perl 5.18.2 in Ubuntu 14.04 with Bash as default shell. Instead of tarring files I ran "ls -ao" after changing directories, as in the example below.

system("cd ~/jobs; ls -ao; cd ..");

Replies are listed 'Best First'.
Re^4: cd in perl not working?
by afoken (Chancellor) on Aug 14, 2014 at 19:08 UTC
    Put the commands in one system() call, separated by semicolons.

    I see the following problems with this way:

    • Separating commands with semicolons may not work with all shells on all operating systems.
    • Using semicolons (on Unix and derivates) ignores the return values of the commands. cd may fail, too, so you may end up executing commands in the wrong directory. OOPS!
    • You mess with the shell. Shells tend to behave very different depending on operating system, shell version, shell configuration. Have a look at http://www.in-ulm.de/~mascheck/various/ for some details. You need to know the exact shell behaviour when you pass parameters to the invoked program. Do you need to quote? How to quote? How to quote quote characters inside the parameters?
    • The extra shell invoked by using the string form of system wastes resources.

    Using perl's chdir around system or between fork and exec avoids chaining commands, and using the list form of system or exec totally avoids the extra shell with all of its problems.

    Alexander

    --
    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
      Good points all. Agreed then, and this will come in handy in a few days for something I'm working on. Thanks for the critique.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1097213]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (5)
As of 2024-04-23 21:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found