0

I am writing a perl script where I need to pass a perl variable into backticks and also the variable should be declared inside of double quotes into that backticks. ex : my $variable=`df -Ph | grep -i "$var1"`

Ravi kumar
  • 129
  • 3
  • 9
  • I saw this thread already but I didnt get it what I need. In my query the command which I am going to execute inside of backticks is very complicated only which should contain multiple double quotes, single quotes, forward slashes at all.. when I am passing the perl variable inside of double quotes its not taking up. – Ravi kumar Aug 07 '15 at 03:22

1 Answers1

5

I think what you're asking is that you have something which contains shell meta-characters (like quotes and slashes). You want to use that in a shell command, but you don't want the meta-characters to be treated literally. For example...

my $search = q[don't look now];
my @results = `df -Ph | grep -i $search`

There's several ways to deal with this. Rather than fiddle around with shell quoting, simplest is to escape all the meta-characters. Perl has quotemeta to do this.

my $search = q[don't look now];
my $q_search = quotemeta($search);  # don\'t\ look\ now
my @results = `df -Ph | grep -i $q_search`

Or you can do it in place with \Q and \E.

my $search = q[don't look now];
my @results = `df -Ph | grep -i \Q$search\E`

Instead I would recommend avoiding the shell as much as possible, it introduces incompatibilities and security holes. You need to do the df in shell, but do the grep in Perl.

my $search = q[don't look now];
my @results = grep /\Q$search\E/i, `df -Ph`;
Schwern
  • 153,029
  • 25
  • 195
  • 336