You can write your input loop so that you don't repeat yourself. Also, I think you probably do not want to allow port numbers ten digits long. It's probably best to test whether the number is in an acceptable range.

my $sshport; while ( $sshport !~ /^[1-9]\d+$/ || $sshport > 65535 ) { print " Please Enter valid ssh port number:\n"; chomp( $sshport = <STDIN> ); }

It might be even better to use something like IO::Prompt.

It's probably not necessary to test whether the line matches the pattern you want to replace before doing the replacement. If the pattern in the replacement doesn't match, nothing will be done anyway. That said, maybe you really did intend for the replacements to be done in circumstances slightly different than when the replacement matches. The code below behaves a little differently than yours, but I think it's closer to what you meant.

while (<SSHD_CONFIG>){ s/^Port.+/Port $sshport/i; s/^#Port\s.+/Port $sshport/i; print SSHD_CONFIG_NEW $_; }

You could even make those two replacements into one (s/^(?:Port|#Port\s).+/Port $sshport/i).

You should check whether rename worked:

rename('sshd_config','sshd_config.old') or die "Can't rename sshd_config: $!"; rename('sshd_config.new','sshd_config') or die "Can't rename sshd_config.new: $!";

In reply to Re: Defactor this code by kyle
in thread Defactor this code by xerophyte

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.