I have a very short tutorial perl script:
#!/usr/bin/perl
print "The date is ",`date`;
print "The date is `date`",".\n";
$directory=`pwd`;
print "\nThe current directory is $directory.";
and the output:
The date is Sat Jul 2 17:04:58 PDT 2011
The date is `date`.
The current directory is total 20
-rwxr-xr-x 1 yan yan 433 2011-07-02 15:58 36
-rwxr-xr-x 1 yan yan 313 2011-07-02 16:29 43
-rwxr-xr-x 1 yan yan 116 2011-07-02 16:51 45
-rwxr-xr-x 1 yan yan 149 2011-07-02 16:53 46
-rwxr-xr-x 1 yan yan 145 2011-07-02 17:02 47
But if I just run pwd I got:
yan@ubuntu:~/bin/blackperl$ pwd
/home/yan/bin/blackperl
Any logical explanation to the mystery here? thanks a lot!
A possible explanation for the mystery:
You have some program named
pwdin the command search path (i.e. in one of the directories named by the PATH environment variable) which does these strange things. When executingpwdin your interactive shell (bash) or in a shell script (dash), you get the buildin commandpwd, which prints the current working directory, as it should.On the other hand, in your Perl source line
Perl does not invoke the system’s shell by using the C
system()function, but instead directly executes thepwdcommand in the path (using theexecvp()call in a forked process), since the command looks simple enough (a simple command, in bash terminology). If thispwdbinary is not the usual/bin/pwdbinary (which also simply prints the current directory), but instead does something likels -l, we get the observed behaviour.The real solution would be to fix your PATH and/or remove the bogus
pwdbinary. Usewhich pwdto find out where it is (ortype -a pwdon bash).A solution from the Perl side would be to force a shell call:
This forces Perl to call the shell instead of directly executing the program. (More generally, any shell metacharacter has this effect. This is described only for Perl’s system function, not for the quote-execute operator.)
In this case Perl would invoke
/bin/sh, which in Ubuntu (at least in current versions, I’m not sure about your 9.10) isdash(Debian Almquist Shell) instead ofbash(GNU’s Bourne Again Shell). Dash is a much simpler (and faster)shimplementation than bash, but for things likepwdthere should be no difference (it is a buildin in my dash, too), as long as you have no aliases or shell functions defined in one shell and not the other.Of course, a better solution would be to use Perl’s Cwd module, as recommended in the answer by toolic.
Thanks to ikegami for explaining the semantics of the backticks operator to me in the comments to the question.