3

Can anyone show me, how to use shell command result in Perl script ?

#!/usr/bin/perl
$whoami=`whoami`;
system ('cd /var/home/'.$whoami.'/htdocs');
print $whoami;

Script output

[user1@srv _1]$ ./sys.pl
sh: line 1: /htdocs: No such file or directory
user1

I want to change dir to /var/home/user1/htdocs

1
  • please note that none of the solutions (and your corrected code) will change the working directory of your program!! Commented Feb 27, 2012 at 13:22

3 Answers 3

4

$whoami contains the endline character \n, which causes your command string to look like:

cd /var/home/user1
/htdocs

You should use chomp to delete the trailing newline from $whoami:

my $whoami = `whoami`;
chomp $whoami;
Sign up to request clarification or add additional context in comments.

Comments

3

This can be accomplished w/o shelling out:

#!perl
my $dir = '/home/'.getlogin().'/htdocs';
chdir $dir;

Comments

2
#!/usr/bin/perl

$whoiami=`whoami`;

print "$whoiami";

chomp $whoiami;
system ("cd /home/$whoiami/reports");

print $whoiami;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.