CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



iphone
User

Dec 20, 2010, 11:20 PM

Post #1 of 4 (3930 views)
How to check for an empty array in perl? Can't Post

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

Post #2 of 4 (3920 views)
Re: [iphone] How to check for an empty array in perl? [In reply to] Can't Post

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

Post #3 of 4 (3907 views)
Re: [shawnhcorey] How to check for an empty array in perl? [In reply to] Can't Post

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

Post #4 of 4 (3687 views)
Re: [iphone] How to check for an empty array in perl? [In reply to] Can't Post

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


 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives