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!

Calling Subroutines

Status
Not open for further replies.

CJason

Programmer
Oct 13, 2004
223
0
0
US
Is there a difference between using "&", vs. not using it, to call subroutines?

For example, is:
&doit();
&doit2($var);
&This::Doit3($var);

this same as:
doit();
doit2($var);
This::Doit3($var);

Thanks!
 
Almost the same. Using the "&" sigil will ignore any prototypes that may be declared in the subroutine. Personally, I only use that when dealing with subroutine references.

See "perlsub" for more.
 
Although it's not very good practice, to call a subroutine which name is stored in a variable, but nevertheless if you want to do that, you need to use the &-operator:
Code:
sub g1 {
  my $name = shift;
  return "Hallo $name\n"
}

sub g2 {
  my $name = shift;
  return "Good Morning $name !\n"
}

my $name = "Joe";
my $greetings = "g1";
print &$greetings($name);
$greetings = "g2";
print &$greetings($name);
So Perl knows that you want to call a subroutine. Without the &-operator this doesn't work.
 
To call an anonymous function, you need & too:
Code:
my $lambda = sub {
  my $name = shift;
  return "Good Night $name !\n"
};

my $name = "Joe";
print "$lambda\n";
print &$lambda($name);
 
quoted from the document ishnid mentioned (perlsub):

A subroutine may be called using an explicit & prefix. The & is optional in modern Perl, as are parentheses if the subroutine has been predeclared. The & is not optional when just naming the subroutine, such as when it's used as an argument to defined() or undef(). Nor is it optional when you want to do an indirect subroutine call with a subroutine name or reference using the &$subref() or &{$subref}() constructs, although the $subref->() notation solves that problem. See perlref for more about all that.

I think mikrom is saying its not a good idea to use soft references, which his example code shows, in which case what he says is true. Use a hard reference instead.

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

Part and Inventory Search

Sponsor

Back
Top