Sang.P Sang.P - 11 months ago 82
Perl Question

Perl array overriding

I am trying to do sum of the array in my perl code but I was not able to get the right output.

Here is my sample code

use File::Find::Rule;
use Date::Parse;

my ($dir, $type, $fh, $line, $str_1,
$str_2,$str_3, $str_4);

my @array;

$dir = '/dir/test/';
$type = '*';
$str_1 = 'somestr1';
$str_2 = 'somestr2';
$str_3 = 'somestr3';
$str_4 = 'somestr4';

my @files = File::Find::Rule->file()->name($type)->in($dir);

open $out, '>>', "output_log" or die "Unable to open 'output_log' : $!";
print $out "\Logs \n";
print $out "--------------------------\n";
close $out or die "Unable to finish writing output_log : $!";

for my $file (@files) {

open $fh, '<', $file or die "can't open $file: $!";
open $out, '>>', "output_log" or die "Unable to open 'output_log' : $!";

while ( $line = <$fh> ) {

if ( $line !~ /$str_1/ && $line =~ /$str_2/ )
@array = $somevar # result of this loop 2,3

if ( $line !~ /$str_3/ && $line =~ /$str_4/ )
@array = $somevar #result of this loop 2,3,4,5,6


close $out or die "Unable to finish writing output_log : $!";

So Here is what I want

@array = (2,3,2,3,4,5,6)
and sum of @array

but unfornately,if i print this array that is running each and every line but instead i want to write a loop which stores the result in array from both if blocks..
now the code is overriding the @array in the second if block. Hope I made this clear!! Please help

Answer Source

@array = ... overwrites the contents of the array. Use push to add elements to an existing array.

For sum, see sum (or sum0) in List::Util.