Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

Re: Defactor this code

by sfink (Deacon)
on Feb 11, 2007 at 04:57 UTC ( #599427=note: print w/ replies, xml ) Need Help??


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.


Comment on Re: Defactor this code
Select or Download Code
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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (10)
As of 2015-07-07 23: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 (93 votes), past polls