houzhe
houzhe

Reputation: 13

How Perl can execute a command in the same shell with it?

I am not sure whether the title is really make sense to this problem. My problem is simple, I want to write a perl script to change my current directory and hope the result can be kept after calling the perl script. The script looks like this:

if ($#ARGV != 0) {
    print "usage: mycd <dir symbol>";
    exit -1;
}

my $dn = shift @ARGV; 

if ($dn eq "kite") {
    my $cl = `cd ./private`;
    print $cl."\n"; 
}
else {
    print "unknown directory symbol";
    exit -1; 
}

However, my current directory doesn't change after calling the script. What is the reason? How can I resolve it?

Upvotes: 0

Views: 531

Answers (2)

ikegami
ikegami

Reputation: 385847

How Perl can execute a command in the same shell with it?

Unless you have a very atypical shell, shells can only receive commands via STDIN, via its command line, and possibly via a command evaluation builtin.

The first two are out unless the Perl script is the parent of the shell, but you could use the third one indirectly as in the following example.

script.pl:

#!/usr/bin/perl
print "chdir 'private'\n";

bash script:

echo "$PWD"             # /some/dir
eval "$( script.pl )"
echo "$PWD"             # /some/dir/private

Of course, if you use bash, you could hide the details in a shell function.

mycd () {
    eval "$( mycd.pl "$@" )"
}

Allowing you use to use

mycd

or even

mycd foo

Upvotes: 0

paxdiablo
paxdiablo

Reputation: 881553

No, the Perl script will be run in a subprocess so it will not be able to affect the environment of the process that called it.

There are various tricks you can use such as sourcing shell scripts (in the context of the current shell rather than a sub-process), or using bash functions and aliases, but they won't work here.

Upvotes: 1

Related Questions