perl query using -pie

前端 未结 3 532
无人及你
无人及你 2021-01-11 23:47

This works:

perl -pi -e \'s/abc/cba/g\' hellofile

But this does not:

perl -pie \'s/cba/abc/g\' hellofile

3条回答
  •  花落未央
    2021-01-11 23:58

    perl already tells you why :) Try-It-To-See

    $ perl -pie " s/abc/cba/g " NUL
    Can't open perl script " s/abc/cba/g ": No such file or directory
    

    If you use B::Deparse you can see how perl compiles your code

    $ perl -MO=Deparse -pi -e " s/abc/cba/g " NUL
    BEGIN { $^I = ""; }
    LINE: while (defined($_ = )) {
        s/abc/cba/g;
    }
    continue {
        die "-p destination: $!\n" unless print $_;
    }
    -e syntax OK
    

    If you lookup $^I in perlvar you can learn about the -i switch :)

    $ perldoc -v "$^I"
    
        $INPLACE_EDIT
        $^I     The current value of the inplace-edit extension. Use "undef" to
                disable inplace editing.
    
                Mnemonic: value of -i switch.
    

    Now if we revisit the first part, add an extra -e, then add Deparse, the -i switch is explained

    $ perl -pie -e " s/abc/cba/g " NUL
    Can't do inplace edit: NUL is not a regular file.
    
    $ perl -MO=Deparse -pie -e " s/abc/cba/g " NUL
    BEGIN { $^I = "e"; }
    LINE: while (defined($_ = )) {
        s/abc/cba/g;
    }
    continue {
        die "-p destination: $!\n" unless print $_;
    }
    -e syntax OK
    

    Could it really be that e in -pie is taken as extension? I guess so

    $ perl -MO=Deparse -pilogicus -e " s/abc/cba/g " NUL
    BEGIN { $^I = "logicus"; }
    LINE: while (defined($_ = )) {
        s/abc/cba/g;
    }
    continue {
        die "-p destination: $!\n" unless print $_;
    }
    -e syntax OK
    

    When in doubt, Deparse or Deparse,-p

提交回复
热议问题