in reply to Is there a better way to check if an array is empty?

I want this for loop to get executed only when @array has elements.
Then no check is needed.
foreach my $base_p4path (@array) { # Execute once for each element in @array. # Hence *NO* loop iteration if @array is empty. }

Replies are listed 'Best First'.
Re^2: Is there a better way to check if an array is empty?
by iphone (Beadle) on Dec 21, 2010 at 19:08 UTC

    I should have been more specific.Basically I want to push $newfile to another array @newfiles only if the array is empty and the instructions after the push instruction should not be executed.The following works for me but I want to know if there is a better way

    if{ my $newfile="$file\n"; @array = grep(/\Q$newfile\E/,keys %hash); if (!@array) { push @newfiles,$newfile; #last; } next unless (@array); ..................... }
      You are using next, and have an outcommented last, without a loop. You also have an if followed by a block.

      I can't make sense of what you are doing, let alone suggest a better way. I do know that many people prefer to use a consistent indenting, but for some reason, many people asking the questions on Perlmonks seem to prefer some random indentation. (But I've seen worse).

        To say in short again,I am searching for a new file in the keys of a hash and pushing the grep results to an array,if the array is emtpy then only push the new file to another array "@newfiles" and then come out of the loop(that's the reason I added a next)

      This "code" is gobbledygook. @array is not needed. Grep in a scalar context returns the number of matches.
      my @files = (.....some file names...); my %hash = (....keyed upon file names...); my @newfiles; foreach my $file (@files) { push (@newfiles, $file) unless ( grep{/\Q$file\E/}keys %hash ); # pushes the name of $file to @newfiles if no match # is found to the pattern within keys of %hash. }