Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

foreach and if loops

Status
Not open for further replies.

keid

Technical User
Aug 8, 2006
22
DE
If I have read a file as an array (probably not a good way for memory in case of big files). How can I move to the next line after matching a word in the if statement in this case?

Code:
@data=<DATA>;

foreach $elem (@data) { 

if ($elem= ~ m/^RBODY /)
{
exp; #storing info from $elem 
#how can i store info from the next line ?
}

}

 
You could just add a "next;" into your loop. That will read in the next element.
 
I dont want any specific output but storing these values
I need to search for keyword RBODY and print the next line after it
Code:
@data=<DATA>;

foreach $elem (@data) {

 if ($elem=~ m/RBODY/) {
	print $elem;
	next;
 if ($elem=m/NAME/) {print $elem;}
}

}
[\code]

I tried this on this sample data, next did not do as expected.

Sample Data

#comment
RBODY /   227799               0   81942                        
NAME Rigid_Body
RBODY /   227793               0   81943                        
NAME Rigid_Body
 
Sorry, I was asleep. "next" just skips the remainder of the current iteration of the loop. The best solution is probably to set a flag when RBODY is read, and at the start of each iteration take action depending on the flag's value.
 
then use indexing:

Code:
@data=<DATA>;
foreach my $i (0..$#data-1) {
   $data[$i] =~ /RBODY/ && print $data[$i+1];
   $data[$i] =~ /NAME/  && print $data[$i+1];
}

I used $#data-1 because the last element of the array has nothing after it to print so it makes no sense to check the last element for a match.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top