访问/修改perl中的数组

时间:2012-02-23 09:53:13

标签: perl

当我们将元素推送到数组时,有没有办法将它推送到特定的列。

我试图做这样的事情。

push (@array, $val ); .......$val should always go to first column.
push (@array, $val2); .......$val2 should go to second column
push (@array, $val3);........$val3 should go to third 

我尝试给予\但但没有得到正确的结果。

elsif ($line =~/RELATION/){
push (@mystuff, "$line" .",");
$line = &getline;
}

我的示例txt文件如下所示

SEVERITY Warning
NODE OTHER "awssystem"
APPLICATION "AWS"
MSGGRP "OpC"
OBJECT "Audit"
MSGKEY "<$MSG_NODE>:hello"
ACK  "<$MSG_NODE>:hello"
TEXT "Test one two three"
AUTOACTION "echo \"It has to ack after AA\" > /tmp/banack" ACTIONNODE IP 0.0.0.0  "<$OPC_MGMTSV>" ANNOTATE ACK
                      OPACTION "echo `hostname`" ANNOTATE
                      TROUBLETICKET
                      HELPTEXT "Hello what is this"

SEVERITY Warning
NODE OTHER "awssystem"
MSGGRP "OpC"
OBJECT "Audit"
MSGKEY "<$MSG_NODE>:hello"
MSGKEYRELATION ACK  "<$MSG_NODE>:hello"

我的文本文件中有很多类似的条目。我试图只捕获严重性,应用程序,msggrp和对象,在上面的输出应用程序中丢失所以我只需要在找不到应用程序时放一个空白。

我的代码如下所示:

while ($#myarr > 0 )
-------
---
elsif ($line =~/SEVERITY/){
push (@mystuff, "$line" .",");
$line = &getline;
}

我希望我的ouput shld看起来这个

SEVERITY Warning APPLICATION "AWS" MSGGRP "OpC"
SEVERITY Warning                   MSGGRP "OpC"

但我的输出看起来像这样

SEVERITY Warning APPLICATION "AWS" MSGGRP "OpC"
SEVERITY Warning MSGGRP "OpC"

3 个答案:

答案 0 :(得分:1)

怎么样:

#!/usr/bin/perl
use strict;
use warnings;

my %res;
my @res;
while(<DATA>) {
    chomp;
    if (/(SEVERITY)/) {
        push @res,{%res} if $.>1;
        %res = map{$_ => ''}qw/APPLICATION MSGGRP/;
        $res{$1} = $_;
    } elsif (/(APPLICATION|MSGGRP)/) {
        $res{$1} = $_;
    }
}
push @res,{%res};

foreach my $res(@res) {
format STDOUT = 
@<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<< @<<<<<<<<<<<<<<<<<<<<
$res->{SEVERITY}, $res->{APPLICATION}, $res->{MSGGRP}
.
write;
}

__DATA__
SEVERITY Warning
NODE OTHER "awssystem"
APPLICATION "AWS"
MSGGRP "OpC"
OBJECT "Audit"
MSGKEY "<$MSG_NODE>:hello"
ACK  "<$MSG_NODE>:hello"
TEXT "Test one two three"
AUTOACTION "echo \"It has to ack after AA\" > /tmp/banack" ACTIONNODE IP 0.0.0.0  "<$OPC_MGMTSV>" ANNOTATE ACK
                      OPACTION "echo `hostname`" ANNOTATE
                      TROUBLETICKET
                      HELPTEXT "Hello what is this"

SEVERITY Warning
NODE OTHER "awssystem"
MSGGRP "OpC"
OBJECT "Audit"
MSGKEY "<$MSG_NODE>:hello"
MSGKEYRELATION ACK  "<$MSG_NODE>:hello"

<强>输出:

SEVERITY Warning      APPLICATION "AWS"     MSGGRP "OpC"
SEVERITY Warning                            MSGGRP "OpC"

答案 1 :(得分:0)

你是什么意思“推进专栏”?

您可以将值存储在数组中的某个位置

$array[0] = $val ;  # $val is 1. element
$array[1] = $val2 ; # $val2 is 2. element
$array[2] = $val3 ; # ...

这与

相同
push @array , $val , $val2 , $val3 ;

假设@array之前是空的。

答案 2 :(得分:0)

IIUC:

push(@array, $val, $val2, $val3)

相关问题