I have a temp
file with contents:
a
b
c
d
e
When I run sed 's#b#batman\nRobin#' temp
from command line, I get:
a
batman
Robin
c
d
e
However, when I run the command from a Perl scriptL
#!/usr/bin/perl
use strict;
use warnings;
`sed 's#b#batman\nRobin#' temp`
It produces error:
sed: -e expression #1, char 10: unterminated `s' command
What am I doing wrong?
CodePudding user response:
Why run another tool like sed
once you are inside a Perl program? If anything, now you have far more tools and power so just do it with Perl.
One simple way to do your sed
thing
use warnings;
use strict;
die "Usage: $0 file(s)\n" if not @ARGV;
while (<>) {
s/b/batman\nRobin/;
print;
}
Run this program by supplying the file (temp
) to it on the command line. The die
line is there merely to support/enforce such usage; it is inessential for script's operation.
This program then is a simple filter
<> operator reads line by line all files submitted on the command line
A line is assigned by it to $_ variable, a default for many things in Perl
The
s///
operator by default binds to$_
, which gets changed (if pattern matches)print
by default prints the$_
variableUse nearly anything you want for delimiters in regex, see m// and s/// operators
This can also be done as
while (<>) {
print s/b/batman\nRobin/r
}
With /r
modifier s///
returns the changed string (or the original if pattern didn't match)
Finally that's also just
print s/b/batman\nRobin/r while <>;
but I'd expect that with a script you really want to do more and then this probablyisn't it.
On the other side of things you could write it more properly
use warnings;
use strict;
use feature qw(say);
die "Usage: $0 file(s)\n" if not @ARGV;
while (my $line = <>) {
chomp $line;
$line =~ s/b/batman\nRobin/;
say $line;
}
With a line in a lexical variable nicely chomp-ed this is ready for more work.