Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use shell command result in perl script?

Tags:

shell

perl

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

like image 254
user1194977 Avatar asked Aug 14 '26 18:08

user1194977


2 Answers

$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;
like image 126
François Févotte Avatar answered Aug 16 '26 21:08

François Févotte


This can be accomplished w/o shelling out:

#!perl
my $dir = '/home/'.getlogin().'/htdocs';
chdir $dir;
like image 31
SparkeyG Avatar answered Aug 16 '26 21:08

SparkeyG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!