News Forge are running an article titled Command line Perl for sysadmins. I think this is a nice introductory article, it answers some of the questions that come up in the Chatterbox from time to time.

Martin

Replies are listed 'Best First'.
Re: Command line Perl for sysadmins
by davidrw (Prior) on Mar 24, 2006 at 14:44 UTC
    Goo article .. I had few comments though (might be biased from a perl guy side instead of a sysadmin side ;) ):
    • There's no reference material mentioned -- I think it would be extremely useful to have mentioned "man perlrun" and "man perlre" as "For more information" or "Advanced Reading" or something. e.g. -l and -0 are both quite useful too (not saying they should be in the article, but somewhere where an interested party can discover them). Also perl -pe 's/foo/bar/' is given a lot of focus, which is why I think perlre should be mentioned.
    • perl -pe '' foo.txt vs perl -pe '' < foo.txt -- both are used .. IMHO I think it's simpler to just stick to the first one since that one supports taking multiple filenames .. one might be confused by the difference when there really isn't one.
    • find . | xargs perl -p -i.old -e 's/oldstring/newstring/g' I didn't like this example because the find . will spit out directory names which will cause warnings from perl .. Especially in sysadmin context, should be find . -type f
    • perl -e 'for("B","C","D"){`scp command.pl $_:`; `ssh $_ command.pl`; }' Didn't like this example (though admittedly don't have a better one) cause it's trivial (and arguably better) to write in bash: for h in B C D ; do scp command.pl $h; ssh $h command.pl ; done

    One last note, of an additional technique I personally find useful -- just use perl to generate the shell commands, much like xargs. For example:
    # perl -e 'for(<access_log.*>){$a = $_; s/log/log.old/; `cp $a $_`}' ls access_log.* | perl -pe 'chomp; $f0 = $_; s/log/log.old/; $_="cp $f +0 $_\n"' # note: don't use $a # other ways to write it: # | perl -lne 'chomp; print "cp $_ $_.old"' # | perl -pe 's/.+/cp $& $&.old/'
    Now, that can be previewed to make sure it's right, and then either redirected into a file and run as a shell script (which has the advantage of doubling as a log of what was done), or the output can be copy/pasted into the shell or piped to bash. I also use this approach often to generate SQL commands ... e.g. take a data file and create INSERT or UPDATE statements.