将新变量放入预先存在的变量perl中



我有一个脚本,它打印出一个由管道分隔的值字符串。我想做的是,如果$f3字段等于某个值,比如字母C我想把xout打印出来。但是,如果$f3没有填充任何值,我希望N和G为分别打印在$f5和F7文件中。

#!/usr/bin/perl
use strict;
use warnings;
my ( $system, $f2, $f3, $f4, $f5, $f6, $f7 ) = "";
#$f3="C";
my $xout = "$system|$f2|$f3|$f4|$f5|$f6|$f7|n";
if ( defined $f3 && $f3 ne '' ) {
    print $xout;
    print "$f3 is defined n";
} else {
    my $f5 = "N";
    my $f7 = "G";
    print $xout;
    print "the 7th and 8th blocks should have values n";
}

这是输出

 Use of uninitialized value $f2 in concatenation (.) or string at ./test_worm_output line 6.
 Use of uninitialized value $f3 in concatenation (.) or string at ./test_worm_output line 6.
 Use of uninitialized value $f4 in concatenation (.) or string at ./test_worm_output line 6.
 Use of uninitialized value $f5 in concatenation (.) or string at ./test_worm_output line 6.
 Use of uninitialized value $f6 in concatenation (.) or string at ./test_worm_output line 6.
 Use of uninitialized value $f7 in concatenation (.) or string at ./test_worm_output line 6.
 |||||||
 the 7th and 8th blocks should have values

如果f没有注释,我得到:

    (lots of uninitialized values lines)
    ||C|||||
    $f3 is defined

我想要的是,如果f没有定义,如果它没有值,我需要它打印出

    ||||N||G|

最终,行将是这样的(其他字段将具有值)但如果第三个值被填充,我就不能有N或G,如果$f3为空我需要N和G.

    host1||C|||||
    host2||C|||||
    host3||||N||G|
    host4||C|||||
    host5||||N||G|

感谢

在行

my ($system ,$f2,$f3,$f4,$f5,$f6,$f7) = ""  ;

您只是在初始化列表中的第一个变量$system。要初始化列表中的所有变量,您需要RHS:上有相等数量的值

my ($system, $f2, $f3, $f4, $f5, $f6, $f7) = ("", "", "", "", "", "", "");

my ($system, $f2, $f3, $f4, $f5, $f6, $f7) = ("") x 7;

然而,任何时候你发现自己在创建编号的变量(例如f1f2f3),你都应该考虑"数组":

my @fields = ("") x 7;
if ($fields[2] eq "") {
    @fields[4, 6] = ("N", "G");
}
print join("|", @fields), "n";

输出:

||||N||G

(当然,这个代码是毫无意义的,因为我们明确地将$fields[2]设置为空字符串,然后检查它是否等于…空字符串。我认为你的实际代码更复杂。)

在您的情况下,第一个字段看起来与其他字段不同,因此将数据存储在数组哈希中更有意义(假设主机名是唯一的):

use strict;
use warnings;
# Populate the hash 
my %data;
foreach my $host_num (1..5) {
    my @fields = ("") x 6;
    $fields[1] = "C" if $host_num == 1 or $host_num == 2 or $host_num == 4;
    my $host_name = "host" . $host_num;
    $data{$host_name} = [ @fields ];
}
# Print the contents 
foreach my $host (sort keys %data) {
    if ($data{$host}[1] eq "") {
        @{ $data{$host} }[3, 5] = ("N", "G");
    }
    print join("|", $host, @{ $data{$host} }), "n";
}

输出:

host1||C||||
host2||C||||
host3||||N||G
host4||C||||
host5||||N||G

最新更新