Difference between &function and function() in perl [duplicate] - perl

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
When should I use the & to call a Perl subroutine?
In perl scripts, why is that method of invoking the function is written differently some times. I see &function and sometimes function(). Are they both the same and this is just a style that one would want to flaunt? If they are the same, why are they both available, would not one just suffice? I am guessing there is some semantic difference between the both the methods which distinguishes them from each other ... but at what kind of circumstances?
--- Since I cannot answer my own question for timeout reasons -- I am updating the answer in the section of question itself. When I get a chance to update the answer block, I will put it there.
I found the relevant text in 'Learning Perl' book..thanks for the tip though. Chapter 4: Subroutines -- Omitting the Ampersand.
I was more interested in ampersand & usage for perl functions. If a subroutine is already defined before being invoked, then subroutine can be invoked without using & while calling the function similar to invoking the builtin functions. & is also used to distinguish between the builtin functions and the user defined functions if the function to be invoked uses the same name that of one of the builtin function, provided it is defined before being invoked.
Usage of (), is merely to justify the passing of the arguments to the subroutines, while if not used, the default list of current arguments are passed in the form #_. If the arguments are specified in () for a subroutine, it is assumed to be a subroutine and is invoked even if not previously defined while parsing.

It has very specific uses:
& tells Perl to ignore the sub's prototype.
& can allow you to use the caller's #_. (&foo; with no parens or arguments).
goto &foo; and defined &foo.
Getting a reference (e.g. \&foo).
Some people (mostly beginners) use it to distinguish user subs from builtin functions, since builtin functions cannot be preceded by &.

As mentioned by #manatwork and #KeithThompson you can find information in these articles:
A general description - What's the difference between calling a function as &foo and foo()?
Subtle information about using & or not for a function call - perlsub: Perl Subroutines: Description.

Related

Is there an option in the perl command to check for undefined functions?

Background
The perl command has several idiot-proofing command line options described in perldoc perlrun:
-c causes Perl to check the syntax of the program and then exit without executing it.
-w prints warnings about dubious constructs, such as variable names that are mentioned only once and scalar variables that are used before being set, etc.
-T forces "taint" checks to be turned on so you can test them.
After reading through these options, I could not find one that detects undefined functions. For example, I had a function I used called NFD() that imports the Unicode::Normalize package. However, being a perl novice, I did not know if this was already under the fold of the standard perl library or not. And perl -c nor any of the other options uncovered this error for me, rather a coworker noticed that it was somehow undefined (and not inside the standard libraries). Therefore, I was curious about the following:
Question
Is there an option in the perl command to automatically detect if there is an undefined function not already inside an imported package?
I did not know if this was already under the fold of the standard perl library or not.
It sounds like you want to distinguish imported subs from other subs and builtin functions.
If you always list your imports explicitly instead of accepting the defaults like I do, then you'll not only know which subs are imported, you'll know from which module they were imported.
use Foo::Bar; # Default imports
use Foo::Bar qw( ); # Import nothing ("()" also works)
use Foo::Bar qw( foo bar ); # Import subs foo and bar.
Is there an option in the perl command to check for undefined functions?
On the other hand, if you are trying to identify the subs that you call that don't exist or that aren't defined at compile time, then this question is a duplicate of How can I smoke out undefined subroutines?.
Aside from the particular technical details, you can't know if a function will be defined at some time in the future when you plan to use it. As a dynamic language, thinks come into and go out of existence, and even change their definitions, while the programming is running.
Jeffrey Kegler wrote Perl Cannot Be Parsed: A Formal Proof that relied on this idea. The details of the halting problem aren't as interesting as workings of a dynamic language.
And, for what it's worth, those command-line options don't make programs idiot-proof. For example, in Mastering Perl I show that merely adding -T to a program doesn't magically make it secure, as many would have you believe.
What were you doing with Unicode::Normalize? It has an NFD already but your question makes it sound like you were wrapping it somehow:
use Unicode::Normalize qw(NFD);

Perl calling subroutine with leading '&' [duplicate]

This question already has answers here:
When should I use the & to call a Perl subroutine?
(4 answers)
Closed 9 years ago.
Every now and then I see Perl scripts where subroutines are called with a leading '&'.
Is this legacy, or does it give any benefit?
As calling the subroutine without the ampersand sign works as well.
sub mysub {
print "mysub\n";
}
mysub;
&mysub;
Thx/Hermann
Calling with & is generally a code smell that somebody doesn't know what they're doing and are in a Perl4 mindset. In your specific example, it works exactly the same. However, calling with & disables function prototypes, so advanced users may use it in certain circumstances. You should expect to see a comment why next to the call in that case.

Is "my" a function in Perl?

I know that my is used to declare a variable local to a block or file. I have always assumed that my is a keyword in Perl. But I was just told that it's actually a function. One of the proofs is that perldoc puts my under the “Functions” section, see http://perldoc.perl.org/functions/my.html.
How does a function do the job of declaring local variables?
my is not a function, it's just clumped together with functions (in perl documentation) because it works like a function.
If you look at perldoc perlfunc, it is saith,
Here are Perl's functions (including things that look like functions, like some keywords and named operators) arranged by category...
then a bit below that
Keywords related to scoping
caller, import, local, my, our, package, state, use
Specifically, note that the word “keyword” was used there instead of “function”
So that implies that you would find some non-functions (e.g. keywords) under Perl functions A-Z
Another way of saying this: if something is listed under “Functions” in perldoc, it is not necessarily a function – it can be a keyword or named operator which acts like a function.
Yes, by Perl's (very unique) definition, my is a function. The opening paragraph of perlfunc defines "function":
The functions in this section can serve as terms in an expression. They fall into two major categories: list operators and named unary operators.
my is a named operator. But it's special in two ways:
In addition to behaving like a function (that allocates a new variable and returns that variable), it has a compile-time effect.
my ... is a unary operator, but it can accept multiple arguments when parens are used.
If on the other hand you were ask if my was a function by C's definition, then no. my is not a C function. Neither is print, open, chr, etc. Everything in perlfunc is an operator; none of them are functions.
Finally, print, open and chr are far closer to a person's conception of a function than my. To be more precise, few people would consider my to be a function. It's more of a technicality than anything meaningful that it matches perfunc's definition of function.
See also:
What are perl built-in operators/functions?
Why does this [my] variable keep its value

What is the difference between subroutines and scripts in Perl?

I am in the midst of learning Perl, and I have encountered a question. What, exactly is the difference between subroutines and scripts?
A script is just a name for a (usually short) program usually contained in a single file. It's not really a scientific/technical term and therefore is pretty vague - people can refer to a "script" when discussing a 3-line quick program, or a 10000 lines of code program.
Some people refer to ANY Perl program as a "script" - see below for the historical reason. Some people, when they say "a Perl script" as opposed to a Perl "program", mean a relatively simple, relatively short program, frequently structured without using any subroutines/classes/other methods of code organization. Again, there's no standard definition.
As an aside, the reason why Perl programs are frequently called "scripts" is that Perl originally was used for writing scripts that perform work in Unix shell, the way shell scripting languages were used. The term "scripting language" means a language used to control an application, in this case Unix shell.
Of course, since then Perl has grown to become a full fledged programming language, but the word/term remained, sometimes used by inertia, sometimes derogatorily.
A subroutine (also known as a procedure, function, routine, method, or subprogram) is a portion of code within a larger program that performs a specific task and is relatively independent of the remaining code. It is frequently meant to contain code that performs the task which needs to be done several times in your program, or even by multiple programs.
A subroutine is NOT a Perl specific concept, though calling it "subroutine" is done in very few languages (most use the term function, method or procedure).
As a special side note, a "method" - in Perl as well as other languages - is a special type of subroutine which is associated with an object oriented class or an object of that class. The fact that it's merely a special case of a subroutine is, of course, highlighted by the fact that - despite deepest wishes by "Modern Perl" author chromatic - methods in Perl 5 are declared with "sub" keyword, same as regular subroutines.
As noted above, some people, when referring to a Perl program as a "script", imply that it does not contain subroutines (e.g. anything complicated enough to have a subroutine is no longer a "script" but a "program"). But that is not an accepted or formal definition - as stated, there is no definition of what a script is, everyone uses the term any which way they want.
A script is usually a file, which can contain statements and subroutines. A subroutine is something you find within a script.
Subroutines are described in detail in the perlsub manual page.

What compile time features does Perl provide that other languages don't?

Is Perl considered a general purpose programming language?
Reading about it on Wikipedia
Perl has a Turing-complete grammar because parsing can be affected by run-time code executed during the compile phase.[41] Therefore, Perl cannot be parsed by a straight Lex/Yacc lexer/parser combination. Instead, the interpreter implements its own lexer, which coordinates with a modified GNU bison parser to resolve ambiguities in the language.
It is often said that "Only perl can parse Perl," meaning that only the Perl interpreter (perl) can parse the Perl language (Perl), but even this is not, in general, true. Because the Perl interpreter can simulate a Turing machine during its compile phase, it would need to decide the Halting Problem in order to complete parsing in every case. It's a long-standing result that the Halting Problem is undecidable, and therefore not even perl can always parse Perl. Perl makes the unusual choice of giving the user access to its full programming power in its own compile phase. The cost in terms of theoretical purity is high, but practical inconvenience seems to be rare.
So, it says that though Perl has the Turing complete badge, it is different from other languages because gives "the user access to its full programming power in its own compile phase". What does that mean? What programming power does Perl provide me at compiling phase that others don't?
There are no features of Perl that do not appear in any other language. Lisp can do anything (Lisp is an example, here.). So perhaps we can narrow the question down to what are the features of Perl that make wide behavior swings an easy thing to do.
BEGIN blocks (END blocks, too.) which alter the behavior during compile. So I can write Perl code that changes the location of modules to be loaded.
Even the following code might have a different meaning.
use Frobnify;
Frobnify->new->initialize;
Because I could have changed where Frobnify loads from:
BEGIN {
if ( [ localtime ]->[6] == 2 ) {
s|^/var|/var/days/tuesday| foreach #INC;
}
}
So on Tuesdays, I load /var/days/tuesday/perl/lib/Frobnify.pm
Source Filters can programmatically edit the code that will perform. (CAVEAT on source filters!) (crudely and roughly equivalent to LISP macros)
Somewhat along with BEGIN blocks are #INC hooks. As I can modify #INC at the beginning to see change what gets loaded. I can set a subroutine at the front of the #INC array to load anything I want to load. The hook can receive a request to load Frobnify and respond to it by loading Defrobnify.pm.
Somewhat along with this is Symbol Manipuation. After loading Defrobnify.pm, I can do this:
*Frobnify:: = \*Defrobnify::;
Now Frobnify->new creates a Defrobnify object!
Subroutine prototypes are a compile time feature that is more or less exclusive to Perl. Many of Perl's builtin functions impose special types of context on their arguments (scalar, list, reference, code-block, capture). Prototypes are a way of porting some of that functionality over to user defined subroutines.
For example, Perl allows you to effectively generate new syntactic constructs with the (&) prototype. This is used in modules like Try::Tiny to add try and catch keywords to the language:
try {
die "foo";
} catch {
warn "caught error: $_"; # not $#
};
This works because try and catch are declared as sub try (&;#) { ... }. The sub name {...} syntax is equivalent to BEGIN { *name = sub {...} } which means it has a compile time effect. In the case of try, the (&;#) prototype tells the compiler that any time it sees the identifier try, the first argument must be a bare block, and following the block is an optional list.
This is just one example of prototypes, and they are able to do many other things:
$ imposes scalar context on an argument
& imposes code context on an argument
# imposes list context on an argument
% imposes list context (with an even number of elements)
* imposes glob context on the argument
\$ imposes scalar reference context
\# imposes array reference context
... for the rest of the sigils
Due to their power (and absence in other languages) prototypes can be confusing and are best used in moderation. (like every other advanced feature of Perl).
The simple answer is that BEGIN blocks provide Turing-completeness:
BEGIN {
my $foo = turing_machine_simulator($program);
}
BEGIN blocks are executed as soon as the perl compiler sees them. This means that the compiler can be asked to do tasks of arbitrary complexity. Anything Perl can do, it can do during its compilation phase.