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 Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

array modification 2

Status
Not open for further replies.

jriggs420

Programmer
Sep 30, 2005
116
US
I think this question is best posed with an example:
Here's a sample array:
Code:
@array=qw(
       11111
       22222
       33333
       xxmeta
       xxdata
);
There could be more, less, or no 'xx...', and the length of the array varies. Given that, how would I reference the last line in the array that does NOT contain 'xx...'?

I know it looks like homework, but I assure you it has a practical application. Thanks-

Because a thing seems difficult for you, do not think it impossible for anyone to accomplish.
Marcus Aurelius
 
You could loop through the array backwards, and for the first item that does not match, return its index.
 
I have a feeling your sample data is too simple. If the 'xx...' stuff is always at the end then do as Tony mentions, work backwards through the array. If the data is mixed up and you do not know the order or the array might not contain 'xx...' you have to go through the entire array.
 
Code:
@array=qw(
       11111
       22222
       33333
       xxmeta
       xxdata
);

$index = -1;

for my $i (0..$#array) {
   $index=$i if ($array[$i] !~ /^xx/);
}

if ($index == -1) { 
   print "No xx data found\n";
}
else {
   print $array[$index];
}
 
TonyGroves made a very good point.
The only thing you have to do is
Code:
foreach (reverse(@array)) {
    $wanted = $_;
    last if $wanted !~ /xx/;
}


``The wise man doesn't give the right answers,
he poses the right questions.''
TIMTOWTDI
 
Thanks for the help. I had to get a new handle because I couldn't login with the old one, and never heard back from the admins. reverse should do just what since the 'xx' lines will always be at the end of the array-
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top