perl脚本只在perl中输出一行输出文件

时间:2014-09-17 15:04:34

标签: perl

我写了一个脚本来在网上打开一个文件,并在名称中删除所有无线行。它将输出写入不同的文件,但它只在输出文件中记录一行,应该是多行文件。

#!\Perl64\eg\perl -w
use warnings;
use strict;

use LWP::Simple;

my $save = "C:\\wireless\\";
my $file = get 'http://dhcp_server.test.com/cgi-bin/dhcp_utilization_csv_region.pl?region=test';

open( FILE, '>', $save . 'DHCP_Utilization_test.csv' ) or die $!;
binmode FILE;
print FILE $file;
close(FILE);

open( F, "C:\\wireless\\DHCP_Utilization_test.csv" ) || die "can't opern file: $!";
my @file = <F>;
close(F);

my $line;

foreach $line (@file) {
    chomp $line;
    if ( $line =~ m/Wireless /g ) {

        my ($ip,     $rtr,   $mask,    $zip,    $blc, $address, $city,
            $state,  $space, $country, $space2, $noc, $company, $extra,
            $active, $used,  $percent, $extra3, $nus, $construct
        ) = split( /,/, $line );

        my $custom_directory = "C:\\wireless\\";
        my $custom_filename  = "wireless_DHCP.csv";
        my $data             = "$ip $mask $rtr $active $used $percent $nus $construct";

        my $path = "$custom_directory\\$custom_filename";

        open( my $handle, ">>", $path ) || die "can't open $path: $!";
        binmode($handle);    # for raw; else set the encoding

        print $handle "$data\n";

        close($handle) || die "can't close $path: $!";
    }
}

1 个答案:

答案 0 :(得分:4)

我认为问题是因为您使用的是Windows,但之后使用:raw保存文件,然后使用:crlf重新打开该文件。

open( FILE, '>', $save . 'DHCP_Utilization_test.csv' ) or die $!;
binmode FILE;
print FILE $file;
close(FILE);

open( F, "C:\\wireless\\DHCP_Utilization_test.csv" ) || die "can't opern file: $!";
my @file = <F>;
close(F);

因此,我怀疑您的@file数组只包含整行文件的一行。

您可以将代码收紧到以下内容:

#!\Perl64\eg\perl
use strict;
use warnings;
use autodie;

use LWP::Simple;

my $url = 'http://dhcp_server.test.com/cgi-bin/dhcp_utilization_csv_region.pl?region=test';

my $datafile = "C:\\wireless\\DHCP_Utilization_test.csv";
my $wireless = "C:\\wireless\\wireless_DHCP.csv";

getstore( $url, $datafile );

open my $infh,  '<',  $datafile;
open my $outfh, '>>', $wireless;

while (<$infh>) {
    chomp;
    next unless /Wireless /;

    my ($ip,     $rtr,   $mask,    $zip,    $blc, $address, $city,
        $state,  $space, $country, $space2, $noc, $company, $extra,
        $active, $used,  $percent, $extra3, $nus, $construct
    ) = split /,/;

    print $outfh "$ip $mask $rtr $active $used $percent $nus $construct\n";
}