我的perl有多可怕?获取IP地址并返回完全合格的域名的脚本



我邀请你,向我撕开一个新的。

此代码可以完成工作。它获取包含IPS列表的.txt文件,并写入包含其各自完全合格域名的文件。

我想知道该代码写得不好。这里有哪些不良习惯?

我是一个新手和编程的新手。我设法使用Google和Trail and Orror将其放在一起。让它上班是令人满意的,但请告诉我如何改进。

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 "$rown";
    $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 "donen";

例如,{chomp $ row;}行是否需要?我不知道它的作用。

我同样被整个{或die $!} thing。

$!报告了为什么发生故障的原因。如果您无法打开文件,则将指出故障的原因。佩尔瓦(Perlvar)有一个错误变量的部分。

您正在使用Chomp从每行末端删除Newline字符。

编写文件时,打开略有不同时,请考虑使用与代码早期阅读时使用的3个参数版本(另请参阅我给您打开的链接),并以相同的编码方式使用。保持一致是很好的,此方法也更安全。

您在编写的每一行都反复打开fqdn.txt。我只是在循环之前打开它,然后在末尾关闭。

哦 - 您正在使用Autodie,因此不需要or die

哦 - 您也使用了旧式的open,与阅读文件开放相比。

工作中没有太多事情,所以我在一些评论中进行了一些重写,以解释一些事情。仅仅是我的旋转和我们在我所使用的一些标准的旋转,这是不对的。

希望这会有所帮助...

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 "donen";

最新更新