Home: Perl Programming Help: Regular Expressions:
How to check for an empty array in perl?



iphone
User

Dec 20, 2010, 11:20 PM


Views: 7031
How to check for an empty array in perl?

Does the following work or is there a better way?

Code
		@array = {1,2,3}; 
#print "ARRAY @array";
if (!@array) {


}
foreach my $base_p4path (@array)#I want this for loop
to get executed only when @array has elements.
{
}



(This post was edited by iphone on Dec 21, 2010, 12:21 AM)


shawnhcorey
Enthusiast


Dec 21, 2010, 6:43 AM


Views: 7021
Re: [iphone] How to check for an empty array in perl?

If the array is empty, the loop is skipped:

Code
#!/usr/bin/perl 

use strict;
use warnings;

my @array = ();
for my $item ( @array ){
print "item = $item\n";
}


__END__

I love Perl; it's the only language where you can bless your thingy.

Perl documentation is available at perldoc.perl.org. The list of standard modules and pragmatics is available in perlmodlib.

Get Markup Help. Please note the markup tag of "code".


iphone
User

Dec 21, 2010, 11:07 AM


Views: 7008
Re: [shawnhcorey] How to check for an empty array in perl?

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

Code
if{ 
my $newfile="$file\n";
@array = grep(/\Q$newfile\E/,keys %hash);
if (!@array)
{
push @newfiles,$newfile;
#last;
}
next unless (@array);
.....................
}



rovf
Veteran

Dec 29, 2010, 4:00 AM


Views: 6788
Re: [iphone] How to check for an empty array in perl?

I don't know what the 'next' is doing in your code, since you are not in a loop.


Quote
I want to push $newfile to another array @newfiles only if the array is empty


This could be done by



Code
push @newfiles,$newfile unless @array;


but you also say:


Quote
and the instructions after the push instruction should not be executed.


In this case, I think an 'if' is the cleanest solution:


Code
if(@array) { 
.....
} else {
push @newfiles,$newfile;
}