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

Array help

Status
Not open for further replies.

ejaggers

Programmer
Feb 26, 2005
148
US
Can you find the element number of an array using foreach?
for instance if $array[50] = 'HELP';

foreach ( sort @array ) {
print 'element number' if ( /HELP/ );
}
I want to print the 50.
 
You'll have to iterate through all the elements in the array. This should get you started.
Code:
my @array;
$array[50] = 'HELP';

my $index_number;
foreach my $i (0..$#array) {
	if (($array[$i] || "") =~ m/HELP/) {
		$index_number = $i;
		last;
	}
}

if (defined $index_number) {
	print "String found at index: $index_number\n";
} else {
	print "String not found.\n";
}
You may want to consider anchors on your search pattern otherwise any element that had HELP in it would be just as good as another.
 
I'm curious, what is the (|| "") part for?

if (($array[$i] || "")

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Never mind, I read the explanation in the other thread.

------------------------------------------
- Kevin, perl coder unexceptional! [wiggle]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top