开发者

What does Perl's -p command-line switch do?

perl -p -i.bak -开发者_如何学运维e 's/search_str/replace_str/g' filename

What do -p, -i.bak s/ and /g mean?


  • -p: assume 'while (<>) { ... }' loop around program and print each processed line too.
  • -i.bak: change the input file (filename) inplace and create the file filename.bak as backup.
  • s in s/: to mark substitution
  • g - make the substitution globally..that is don't stop after first replacement.


From perlrun:

-p

causes Perl to assume the following loop around your program, which makes it iterate over filename arguments somewhat like sed:

  LINE:
    while (<>) {
        ...             # your program goes here
    } continue {
        print or die "-p destination: $!\n";
    }


This piece of code:

perl -p -i.bak -e 's/search_str/replace_str/g' filename

Is essentially the same as:

#! /usr/bin/env perl
$extension = '.orig';
LINE:
  while (<>) {
    # -i.bak
    if ($ARGV ne $oldargv) {
      if ($extension !~ /\*/) {
        $backup = $ARGV . $extension;
      } else {
        ($backup = $extension) =~ s/\*/$ARGV/g;
      }
      rename($ARGV, $backup);
      open(ARGVOUT, ">$ARGV");
      select(ARGVOUT);
      $oldargv = $ARGV;
    }

    s/search_str/replace_str/g;

  } continue {
    print;  # this prints to original filename
  }

select(STDOUT);


It will automatically read a line from the diamond operator, execute the script, and then print $_.

For more details visit the following link.

Perl -p


See perldoc perlrun.

This one-liner changes every occurrence of search_str to replace_str in every line of the file, automatically printing the resulting line.

The -i.bak switch causes it to change the file in-place and store a backup to another file with the .bak extension.


1.causes perl to assume the following loop around your script, which makes it iterate over filename arguments somewhat like sed:

  1. Note that the lines are printed automatically. To suppress printing use the -n switch. A -p overrides a -n switch.

link text

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜