1

I am trying to take a file, and copy it to an output file and then find all the <k> and make them into <p> instead. I want to use regex.

  while (<INPUTFILE>)
  {
         if($_ != "<p>")
         {
                print OUTPUTFILE "$_\n";  
          }

          else
          {
              print OUTPUTFILE "<k>";  
            }

  }

I was trying something like this but I guess the $_ variable takes each line at a time. So It would prob be better to use write the entire file then try the regex search and replace? for that I have tried:

  $_ =~ s/<k>/<p>/g;
5
  • Do you have a sample of the file content? Is it simply either <p> or <k> on lines or is there more content? Commented Oct 24, 2013 at 19:39
  • Your code seems to be looking for <p> in the input and printing <k> when it finds it. Your description has the inverse logic. Which is right? Commented Oct 24, 2013 at 19:40
  • Always use use strict; use warnings;. It would have found a major error. Commented Oct 24, 2013 at 19:40
  • Unless you use chop or chomp, $_ already ends with a newline. So you shouldn't add one when you print OUTPUTFILE "$_";. Commented Oct 24, 2013 at 19:42
  • To expand on @Barmar's comment: since you aren't chomping the input, $_ contains a newline, your if($_ != "<p>") will always be !=, since your test literal has no newline - unless your input file ends with a line that isn't newline-terminated Commented Oct 24, 2013 at 19:44

4 Answers 4

5

A line at a time is not a problem.

while (<>)
   s/<k>/<p>/g;
   print;
}
Sign up to request clarification or add additional context in comments.

Comments

1

As @ikegami suggests, one line at a time is no problem. Alternatively, you could do this in a single search and replace:

{
   local $/ = undef;
   my $data = <INPUTFILE>;
   $data =~ s/<k>/<p>/g;
}

This would do the search and replace in a single operation and might be faster and/or more efficient for larger files.

Comments

0

From the command line

perl -pe 's/<k>/<p>/g' <infile >outfile

Simples.... :-)

Look up 'change record separator' if you are concerned about newline effects

Comments

0

If you really want to treat the whole file in one time :

BEGIN { $/ = undef; $\ = undef; }
LINE: while (defined($_ = <ARGV>)) {
    s/<k>/<p>/g;
    print $_;
}

From :

perl -0777 -MO=Deparse -pe 's/<k>/<p>/g; print;'

1 Comment

I think you were trying to slurp the file, but 1) you weren't (so I fixed it), and 2) it's useless. // And now you added /m (which changes what unused ^ and $ match) and /s (which changes what unused . matches). Also useless.

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.