对于一个数组我检查在foreach循环中设置一些条件。只有当它为真时,我才想将$_
分配给另一个数组..但是简单的@stale = $_;
没有附加到它......也不是push
或任何其他函数。 。
知道如何解决这个问题吗?
编辑:OP评论的代码
# To give a generic ORACLE_HOME and HOSTNAME path for all the instances.
#
#using shell ENV variable in perl
my $home = $ENV{'ORACLE_HOME'};
#
#concatenating the paths
my $subdir = "/ccr/hosts/";
my $subdir1 = $home.$subdir;
my $host = "`hostname`/state/review";
my $subdir2 = $subdir1.$host;
#
#assigning each row of command output to an array
@infile = `ls -ltr $subdir2`;
#
#printing each value of the array i.e. file details
foreach (@infile) {
chop($_);
$m_age = -M $_;
if (($stale = `date` - $m_age) < 1.0) {
#
#
#change/correct this line :(
#
#
printf "\nFile %s was last modified 24hrs back. stale collections. \n" , $_ , $m_age ,$stale;
push @stale_files , $_;
}
else {
@not_stale_files = $_[$q++];
}
$count++;
}
print "\n for stale:\n";
foreach $i (@stale_files) {
print "$stale_files[$i]\n";
}
此外,每次循环执行时,$_
值都应附加到@stale
。但只有$_
的最后一个值(在上次循环运行期间获得)才会被分配到@stale
。
答案 0 :(得分:1)
好的,让我们回顾一下编辑过的代码
请使用
use warnings;
use strict;
代码中的:它将帮助您检测错误
# To give a generic ORACLE_HOME and HOSTNAME path for all the instances.
#
#using shell ENV variable in perl
my $home = $ENV{'ORACLE_HOME'};
#
#concatenating the paths
my $subdir = "/ccr/hosts/";
my $subdir1 = $home.$subdir;
您不需要复杂的构造
my $subdir1 = $ENV{'ORACLE_HOME} . '/ccr/hosts';
就够了
下一行不起作用:后退标记不会在"
引用的字符串中展开
my $host = "`hostname`/state/review";
my $host = `hostname` . '/state/review';
my $subdir2 = $subdir1.$host;
#
#assigning each row of command output to an array
@infile = `ls -ltr $subdir2`;
此处@infile
将包含多个文件。每个元素的输出都为ls -ltr
。像
total 16
-rw-r--r-- 1 corti corti 94 Sep 14 11:40 test.pl~
-rw-r--r-- 1 corti corti 979 Sep 14 11:49 test.pl
#
#printing each value of the array i.e. file details
foreach (@infile) {
chop($_);
这里你正在做-M -rw-r--r-- 1 corti corti 94 Sep 14 11:40 test.pl~
。
$m_age = -M $_;
if (($stale = `date` - $m_age) < 1.0) {
#
#
#change/correct this line :(
#
#
printf "\nFile %s was last modified 24hrs back. stale collections. \n" , $_ , $m_age ,$stale;
这是对的。问题出在$_
push @stale_files , $_;
}
else {
$_
是@infile
的元素。你想要实现$_[]
的目标是什么?什么是$q
?
@not_stale_files = $_[$q++];
}
$count
永远不会被初始化
$count++;
}
print "\n for stale:\n";
foreach $i (@stale_files) {
print "$stale_files[$i]\n";
}
答案 1 :(得分:0)
使用“push @stale, $_;
”(添加到数组的末尾)而不是“@stale = $_;
”(完全替换数组的现有内容)应该适用于这种情况。
修改:证明push
做了所要求的事。
代码:
#!/usr/bin/env perl
use strict;
use warnings;
my @numbers = (1, 8, 3, 5, 2, 8, 9, 0);
my @stale;
for (@numbers) {
if ($_ < 5) {
printf "\nNumber %s is less than five.\n", $_;
push @stale, $_;
}
}
print join ", ", @stale;
print "\n";
输出:
$ ./add_to_array.pl
Number 1 is less than five.
Number 3 is less than five.
Number 2 is less than five.
Number 0 is less than five.
1, 3, 2, 0
$