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

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Beginner:
I dont understand this particular sub



Dec 5, 2013, 6:36 AM

Post #1 of 2 (1671 views)
I dont understand this particular sub Can't Post

I dont understand what is going on with this sub. I have the need to compare 3 vars and searched the web for examples. I found this but dont understand what the sub is doing


my $a = 2;
my $b = 2;
my @arr = qw( 2 2 2 );

if (all_equal_ints($a, $b, @arr)) {
print "They're all equal!\n"
} else {
print "They're not all equal!\n";

sub all_equal_ints {
my $first = shift; #why shift and where is $first coming from
for (@_) { #I understand this is reading the list of vars passed
return 0 unless $first == $_; #Not sure what this is saying
return 1; # suppose if the test above fails, sets return to "true"

Thanks for helping this nooby out in advance !! My transition from Ksh to perl continues with lots of frustration and "stucks". .. but Im determined. Crazy

(This post was edited by popeye on Dec 5, 2013, 6:36 AM)

Veteran / Moderator

Dec 5, 2013, 7:22 AM

Post #2 of 2 (1661 views)
Re: [popeye] I dont understand this particular sub [In reply to] Can't Post

my $first = shift; #why shift and where is $first coming from

The all_equal_ints() sub is being passed a list of 5 values. Inside the sub those values are accessed via the @_ array. The shift function takes (removes) the first value in the @_ array and assigns that value to the lexical var $first.

See: perldoc -f shift

return 0 unless $first == $_; #Not sure what this is saying

return 0 unless says to exit the sub and return 0 to the calling block if the next part of the statement is/returns false. $first == $_; is comparing the value in $first to the value is $_ to see if they are numerically equal. If they are not equal, false is returned to the earlier portion of the statement which causes the return 0 to be executed. If they are equal, it does nothing and moves on to the next iteration of the for loop.

I would normally write that return statement like this, which might be easier for you to understand.

return 0 if $first != $_;

or if you wish the more verbose syntax.

if ($first != $_) { 
return 0;


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

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