2

so I know that there are many ways of doing what I am asking for, but all that I have found is not helping me for what I am trying to do. It is supposed to be a simple find and replace script using stdin and stdout. I have a script called replace.pl and this is what i have in it:

#!/usr/bin/perl
use strict;
use warnings;

while(<STDIN>){
  $_ = s/$ARGV[0]/$ARGV[1]/g;
  print STDOUT $_;
}

When I run echo "replace a with b please" | replace.pl 'a' 'b' all I get back is a "1". My desire output is "replace b with b please" but what ever I try to do, it is not changing it. Could any one tell me what i am doing wrong here?

2 Answers 2

3

Try

s/$ARGV[0]/$ARGV[1]/g;

instead of

$_ = s/$ARGV[0]/$ARGV[1]/g;

as s/// returns 1 when substitution was successful.

You can also quote search pattern if it should be literal string (not a regex),

  s/\Q$ARGV[0]\E/$ARGV[1]/g;
Sign up to request clarification or add additional context in comments.

1 Comment

oh my gosh... lol thanks. I almost freaking had it. I cant believe i missed that. thank you.
1

From perlop:

  • s/PATTERN/REPLACEMENT/msixpodualgcer

    Searches a string for a pattern, and if found, replaces that pattern with the replacement text and returns the number of substitutions made. Otherwise it returns false (specifically, the empty string).

That's why the code sets $_ = 1. You just want to do s/$ARGV[0]/$ARGV[1]/g; for its substitution side-effect, without assigning its return value to $_.

while (<STDIN>) {
    s/$ARGV[0]/$ARGV[1]/g;
    print;
}

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.