CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
subroutines in perl

 



chander1986
Novice

Mar 19, 2009, 11:05 PM

Post #1 of 4 (414 views)
subroutines in perl Can't Post

I am writing a subroutine which checks whether the passed value is present in array or not. The following is the code that i have written

Code
 @temp_array = {1,2,3,4}; 

if(&isPresent(1) == 1) {
print "HI";
}
else {
print "Hello";
}






sub isPresent {
foreach $temp (@temp_array) {
if($_ == $temp) {
$found =1;
last;
}
else {
$found =0;
}

}
return $found;
}


The problem with this code is that my subroutine never returns 1, so my control always goes in the else loop. I am not able to figure out where i am going wrong


KevinR
Veteran


Mar 19, 2009, 11:34 PM

Post #2 of 4 (412 views)
Re: [chander1986] subroutines in perl [In reply to] Can't Post

Your code has a few problems, possibly the biggest is the use of curly brackets to define the array:

@temp_array = {1,2,3,4};


that creates a reference to a hash instead of an array, you should use parentheses:

@temp_array = (1,2,3,4);

You are also not passing arguments to the subroutine nor using the correct variables to try and find if a number is in the array. Here is the code written properly:


Code
use strict; 
my @temp_array = (1,2,3,4);
if (&isPresent(1,\@temp_array)) {
print "HI";
}
else {
print "Hello";
}

sub isPresent {
my ($find, $array) = @_;
foreach my $n ( @{$array} ) {
return 1 if ($n == $find);
}
return 0;
}


Ask questions if you need something explained
-------------------------------------------------


chander1986
Novice

Mar 19, 2009, 11:37 PM

Post #3 of 4 (411 views)
Re: [KevinR] subroutines in perl [In reply to] Can't Post

I am not quite sure what the following code does:

my($find,$temp_array) = @_


KevinR
Veteran


Mar 20, 2009, 12:12 AM

Post #4 of 4 (409 views)
Re: [chander1986] subroutines in perl [In reply to] Can't Post

Within a subroutine the array @_ contains the parameters passed to that subroutine. The line you questioned assigns those parameters to lexical variables used in the subroutine. For more details read perlsub:

http://perldoc.perl.org/perlsub.html
-------------------------------------------------

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives