in reply to Defactor this code

I would have written that process as follows:
use strict; die "Usage: $0 port#\n (where port# is a number > 9 and < 65536\n" if ( @ARGV != 1 or $ARGV[0] !~ /^[1-9]\d+$/ or $ARGV[0] >= 65536 ) +; my $sshport = shift; my $filename = "sshd_config"; open (SSHD_CONFIG,$filename) or die ("can't open $filename for reading: $!"); open (SSHD_CONFIG_NEW,">","$filename.new") or die ("can't open $filename.new for writing: $!"); while (<SSHD_CONFIG>){ s/^(#?)port.+/$1Port $sshport/i; print SSHD_CONFIG_NEW; } ( rename $filename, "$filename.old" and rename "$filename.new", $filename ) or die "rename failed: $!"
(updated to fix the tests on $ARGV[0])

The points I would make about this, relative to the OP version:

Replies are listed 'Best First'.
Re^2: Defactor this code
by xerophyte (Initiate) on Feb 10, 2007 at 20:29 UTC
    Awesome, i feel learned lot fro this defector, i have one problem the sshd_config sometime looks like this
    #Port 22
    Port 4444
    
    #Protocol 2,1
    #ListenAddress 0.0.0.0
    #ListenAddress ::
    
    After we modify the file with above code it becomes like this
    Port 4444
    Port 4444
    
    it should be lie
    Port 4444
    
    Thanks again
      i have one problem the sshd_config sometime looks like this
      #Port 22 Port 4444
      After we modify the file with above code it becomes like this
      Port 4444 Port 4444

      Right, that's what your code in the OP does, and that's what I mentioned in my third "bullet" paragraph as probably being a bug.

      Now, you seem to be saying that you simply want to delete all commented lines (the ones beginning with "#"), which is easy enough to do:

      while (<SSHD_CONFIG>) { next if ( /^#/ ); s/^port.+/Port $sshport/i; print SSHD_CONFIG_NEW; }
      But some people prefer to leave the comment lines in, because sometimes these lines hold important information that might be useful someday (e.g. documentation, or details about a prior or alternative configuration that might be needed when conditions change).

      That's why the version in my first reply used the parens and the "$1" in the s/// statement, to preserve the "#" character while changing the port number. Actually, I think it may be best to retain the comment lines unchanged, and only edit the "uncommented" line -- this also turns out to be the simplest method:

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