http://www.perlmonks.org?node_id=599427


in reply to Defactor this code

For things like this, it's nice to be familiar with some of the more esoteric shortcuts perl offers. I typically do something like that with a one-liner, probably something like:
perl -i.old -lne 'if (/^[\s#]*Port/i) { print "Port 1234" unless $done +++ } else { print }' sshd_config
Although given that the order of directives in the sshd_config file doesn't matter, that could just be
perl -i.old -lne 'print unless /^[\s#]*Port/i; END{print "Port 1234"}' + sshd_config
I don't see a whole lot of point in prompting for the port number, but if you want it separated out of the script you could use
PORT=1234 perl -i.old -lne 'print unless /^[\s#]*Port/i; END { print " +Port $ENV{PORT}" }' sshd_config
or
perl -i.old -lne 'BEGIN { $sshport = pop }; print unless /^[\s#]*Port/ +i; END { print "Port $sshport" }' sshd_config 1234
All of these are untested, sorry.

Replies are listed 'Best First'.
Re^2: Defactor this code
by smahesh (Pilgrim) on Feb 11, 2007 at 07:34 UTC
    Hi sfink,

    Your solution is succint and will most likely work as the OP intended. But, I would recommend the OP to use his/her version updated with the comments from other monks. Since the OP is new to perl, a more verbose solution instead of a succint solution may be better in terms of simplicity, understandability and maintainability.

    Having said that, I would also strongly recommend the OP to try to understand the perl one-liner version - as a good learning exercise.

    Regards,
    Mahesh