How terrible is my Perl? Script that accepts IP addresses and returns Fully qualified domain names

I invite you to tear me new.

This code does its job. It receives a .txt file containing a list of IP addresses and writes a file containing the corresponding fully qualified domain names.

I want to know how this code is poorly written. What are bad habits here?

I am new to Perl and programming. I managed to put this together using google and trail and error. Achieving his work was satisfactory, but please tell me how I can improve.

use strict;
use warnings;
use Socket;
use autodie;


my $filename = 'IPsForFQDN.txt';
#File with list of IPs to lookup.
#One IP address per line like so:
#10.10.10.10
#10.10.10.11
#10.10.10.12
#etc...


open(my $fh, '<:encoding(UTF-8)', $filename)
    or die "Could not opne file '$filename' $!";
my $fqdn = '';

while (my $row = <$fh>) {
    chomp $row;

    print "$row\n";
    $fqdn = gethostbyaddr(inet_aton($row), AF_INET);
    print $fqdn;
    print "\n";
    open FILE, ">>fqdn.txt" or die $!;
    print FILE $fqdn;
    print FILE "\n";
    close FILE;

}
print "done\n";

For example, do you need the string {chomp $ row;}? I have no IDEA what he is doing.

I am also puzzled by the whole {or die $ !;}.

+4
3

$! , - . , , . perlvar .

chomp, .

open , 3, ( . , ), . , .

+2

fqdn.txt , . .

Oh - autodie, or die .

Oh - open, .

+2

, , . / , , , .

, ...

use strict;
use warnings;
use Socket;

# initialize variables here.
my $filename = "IPsForFQDN.txt";

# open both file handles - once only
# Note safer expression using 2 commas
open(FH, "<", $filename)
        or die "Could not opne file '$filename' $!";

# open FILE for appending
open FILE, ">>", "fqdn.txt" or die $!;

# use foreach instead of while - easier syntax (may provoke discussion ;-) )
# replaced $fh for FH - use file handles throughout for consitency
foreach my $row ( <FH> )
{
    chomp $row;

    # put a regex check in for comments

    if( $row !~ m/^#/ )
    {
        printf ("Row in file %s \n", $row );

        # initialize $fqdn here to keep it fresh
        my $fqdn = gethostbyaddr(inet_aton($row), AF_INET);

        # formatted print to screen (STDOUT)
        printf ("FQDN %s \n", $fqdn);

        # formatted print to output file
        printf FILE ("%s \n", $fqdn);
    }
}

# close both file handles - once only
close FILE;
close FH;

print "done\n";
+1

Source: https://habr.com/ru/post/1530451/


All Articles