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

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

Replies are listed 'Best First'.
Re^3: Is there a better way to check if an array is empty?
by JavaFan (Canon) on Dec 21, 2010 at 19:27 UTC
    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)

        Your code has no loop! Maybe you need to show a little more of the code? It would be even better to mock up some data and show the result you expect compared with the result you are getting - at present it's not clear because your code doesn't match your comments.

        True laziness is hard work
        and then come out of the loop
        One way of improving your code is to create a loop. Without a loop, you can't come out of it.
Re^3: Is there a better way to check if an array is empty?
by Marshall (Canon) on Dec 23, 2010 at 09:11 UTC
    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. }