2012-02-23 57 views
-1

有没有什么办法,当我们将一个元素推送到一个数组时,我们可以将它推送到特定的列。在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 

我试着给\ t但没有得到正确的结果。

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; 
} 

我希望我的输出中SHLD眼线此

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

但我的输出看起来像这样

SEVERITY Warning APPLICATION "AWS" MSGGRP "OpC" 
SEVERITY Warning MSGGRP "OpC" 
+0

你能解释一下你想要的输出? – Toto 2012-02-23 10:14:31

回答

0

你是什么意思“推到列“?

可以在一定的位置的值存储在数组中

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

这是相同

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

假设@array之前是空的。

+0

对不起,我应该更具体。我的txt文件看起来像这样的东西 – bprakash 2012-02-23 10:42:34

0

IIUC:

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

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"