简体   繁体   中英

Execute Unix command in a Perl script

How I can make the following external command within ticks work with variables instead?

Or something similar?

sed -i.bak -e '10,16d;17d' $docname ; (this works)

Ie, sed -i.bak -e '$line_number,$line_end_number;$last_line' $docname ;

my $result = 
      qx/sed -i.bak -e "$line_number,${line_end_number}d;${last_line}d" $docname/;

Where the line split avoid the horizontal scroll-bar on SO; otherwise, it would be on one line.

Or, since it is not clear that there's any output to capture:

system "sed -i.back '$line_number,${line_end_number}d;${last_line}d' $docname";

Or you could split that up into arguments yourself:

system "sed", "-i.back", "$line_number,${line_end_number}d;${last_line}d", "$docname";

This tends to be safer since the shell doesn't get a chance to interfere with the interpretation of the arguments.

@args = ("command", "arg1", "arg2");
system(@args) == 0 or die "system @args failed: $?"

Furthermore on the manual:

perldoc -f system

I think you should read up on using qq for strings.

You probably want something like this:

use strict;
use warnings;

my     $line_number = qq|10|;
my $line_end_number = qq|16d|;
my       $last_line = qq|17d|;
my        $doc_name = qq|somefile.bak|;
my     $sed_command = qq|sed -i.bak -e '$line_number,$line_end_number;$last_line' $doc_name;|;

print $sed_command;
qx|$sed_command|;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM