Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1131
  • Last Modified:

Perl - foreach loop and else statement

I have the foreach loop in a sub I use, I cannot get the "else" to print if $match is not found, the way I have it below works ok other than I cannot get the  print to work for the else.

Any help would be much appreciated.

foreach my $regions (@regions) {
 open(GCSEA,"/usr/local/bin/adsearch xxx samaccountname=$sam-$regions samaccountname | ");
  while(<GCSEA>) {
   if (/^sAMAccountName: (.*?)/) {
    (my $match) = (/sAMAccountName: (.*)/);
if (defined($match)) {
   print "\t$regions-",$match,"\t";
} else {
   print $regions,"-NotInAd\n";
}
   } 
 }
}

Open in new window

0
bt707
Asked:
bt707
2 Solutions
 
rockiroadsCommented:
get your indentation sorted, it will make life easier to read

Now looking at your code, have you checked the first if? there is no else on that. So your code is only going to print something if it passed the first if condition
Can you confirm it is going pass the first if?

the attached code has been indented properly with the extra else added on the first if

foreach my $regions (@regions) {
	open(GCSEA,"/usr/local/bin/adsearch xxx samaccountname=$sam-$regions samaccountname | ");
	while(<GCSEA>) {
		if (/^sAMAccountName: (.*?)/) {
			(my $match) = (/sAMAccountName: (.*)/);
			if (defined($match)) {
				print "\t$regions-",$match,"\t";
			} else {
				print $regions,"-NotInAd\n";
			}
		} else {
			print "Dodgy\n";
		}
	}
}

Open in new window

0
 
Adam314Commented:
Note that both your first and second if statement are looking for the same thing.  So, if it matches the first time, it will match the second time - and you'll never get to the else for the second if.  In rockiroads code, this would print "Dodgy".

0
 
bt707Author Commented:
Thanks to both for the help, I figured out why I cannot get what I want, it is basically in the first condition and also in the way I put in the if/else statements which both pointed out. I got it working now.

Thanks,
0

Featured Post

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now