Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

-pi -e argv repeater

by jettero (Monsignor)
on Feb 02, 2007 at 15:38 UTC ( #597949=perlquestion: print w/ replies, xml ) Need Help??
jettero has asked for the wisdom of the Perl Monks concerning the following question:

I'm rather fond of the perl -pi -e 's///' type "programs." I began to wonder about techniques that might make it possible to use -pi from the middle of a bigger program, similar to the following, but without forking with system.

Is it possible to somehow repopulate @ARGV and re-invoke the command line switches? or something?

use warnings; use strict; # do many boring things while(<*something*>) { system(qw(perl -pi -e), $program) == 0 or die; } # do many more boring things

Obviously, it'd probably be more appropriate to just write the proper while loop and file copy/renaming code. But changing the file perms and ownerships is cumbersome and I want something slick and easy.

Also, the more I think about it, repopulating @ARGV is pretty simple... duh.

-Paul

Comment on -pi -e argv repeater
Select or Download Code
Re: -pi -e argv repeater
by ikegami (Pope) on Feb 02, 2007 at 15:45 UTC

    Perhaps you'd like

    use constant PIE_NO_BACKUP => ''; sub pie(&$@) { ( my $code, # Code ref local $^I, # PIE_NO_BACKUP, '~', '.bak', etc local @ARGV, ) = @_; local *_; # Protect caller's $_. while (<>) { chomp; $code->(); print($_, "\n"); } } # perl -i -pe 's///' file1 file2 pie { s/// } PIE_NO_BACKUP, 'file1', 'file2'; # perl -i.bak -pe 's///' file? data*.txt pie { s/// } '.bak', map { bsd_glob($_) } 'file?', 'data*.txt';

    Untested.

    Update: Added missing "\n". Created constant for no backup. Added local *_;.

      $^I is apparently all I needed. I had no idea it would be so simple, thanks. I obviously should have just asked on the chatterbox... how embarassing.

      -Paul

      May I ask what the (&$@) in the sub declaration is for?

      I like computer programming because it's like Legos for the mind.

        It's a prototype.

        Without the prototype, you'd have to do
        pie sub { CODE }, SCALAR, LIST
        or
        pie &func, SCALAR, LIST

        With the prototype, you can also do
        pie { CODE } SCALAR, LIST

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://597949]
Approved by liverpole
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (12)
As of 2015-07-03 07:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (48 votes), past polls