On 04/17/2012 08:30 AM, Manfred Lotz wrote:
On Tue, 17 Apr 2012 12:27:32 +0100
Gary Stainburn<gary.stainb...@ringways.co.uk>  wrote:

On Monday 16 April 2012 15:20:35 Paul Johnson wrote:
On Mon, Apr 16, 2012 at 06:53:53AM -0700, Paul.G wrote:
Hi All

Have a question, is it good coding practice to use a&  when
calling a subroutine, or it is not required, or it doesn't matter?

It's good practice not to use it unless you understand exactly why
you would need to use it.

Could someone please expand on this as I seem to always have to do
this. If I 'use strict' and 'use warnings' I get errors if I don't.


One example is this:

#! /usr/bin/perl

use strict;
use warnings;

mysub;

sub mysub {
   print "Hi there\n";
}

If you run this you get an error:
Bareword "mysub" not allowed while "strict subs" in use at ./testsub.pl
line 6. Execution of ./testsub.pl aborted due to compilation errors.


Perl tells you that it has no idea what you mean when you use the
bareword mysub.


Now you have two options to solve it.

1.&mysub;

Using the sigil&  you tell Perl that mysub is a subroutine.

2. mysub();

Usind () after mysub you also tell Perl that mysub is a subroutine.


3.&mysub();

Combining 1. and 2. works also but is not recommended. Hmm, at least I
do no recommend it.


Use 2. and you'll be happy.


There are surely some other situations where using&  might be
appropriate. But this one came into my mind immediately.

overall a good example. but it doesn't show where & might be appropriate. the () is correct and the & isn't. note that calling &mysub is different than calling &mysub() (or mysub()). that is the key reason to not use & for plain sub calls. as i said in my other post, i won't go into the reasons why as it is not important here. you just use () for sub calls and not &. even with code references $mysub->() is correct and &$mysub isn't.

thanx,

uri

--
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to