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

Practice Perl 2

Status
Not open for further replies.

godspeed06

Vendor
Apr 7, 2006
34
US
Greetings,
Consider the script below, where I am expecting "dino" to be retuned, but for some reason is not. --can anyone shed light on this?

Script:
#!perl -w
use strict;

my @names = qw/ fred barney betty dino wilma pebbles bamm-bamm /;
my $results = &which_element_is("dino", @names);

sub which_element_is
{
my($what, @list) = @_;
foreach (0..$#list)
{
if($what eq $list[$_])
{
return $_;

}

}
-1
}
 
#!perl -w
use strict;

my @names = qw/ fred barney betty dino wilma pebbles bamm-bamm /;
my $results = &which_element_is("dino", @names);
print "RESULT: $results\n";
sub which_element_is
{
my($what, @list) = @_;
print "What:$what\n";
print "LIST: @list\n";
foreach (0..$#list)
{
if($what eq $list[$_])
{
print "HEY:$list[$_]\n";
return $list[$_];

}

}
-1
}


dmazzini
GSM System and Telecomm Consultant

 
whats happening is in the foreach loop you are looping through a list of numbers, starting with zero and ending with the last index of the array, which is 6:

foreach (0..$#list)

each number is assigned to $_ with each iteration of the loop, so it goes from zero to 6, which you use to make your comparison correctly:

if($what eq $list[$_])

but then you return only the number of the loop iteration:

return $_;

instead of the value of the position in @list:

return $list[$_];
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top