I have tested the following code with perl 5.8 (codepad) and perl 5.16 . There's probably some deeper principle I'm missing and I'm curious what the logic behind this behavior is. Thanks.
The following simple recursive subroutine reference
use strict;
use warnings;
my $fact = sub {
my $n = shift;
if ($n == 0) {
return 1;
}
return $n * $fact->($n-1);
};
print $fact->(100);
results in the error
Global symbol "$fact" requires explicit package name at line 9.
Execution aborted due to compilation errors.
declaring variable before defining it does not produce this error.
use strict;
use warnings;
my $fact;
$fact = sub {
my $n = shift;
if ($n == 0) {
return 1;
}
return $n * $fact->($n-1);
};
print $fact->(100);
my returns the new lexical, so it can be used to assign to it in the same statement in which it was declared. However, any further references to that name only resolve to that lexical beginning with the next statement.
So separate the declaration:
my $fact;
$fact = sub { ... $fact ... }
This rule is in fact sometimes useful; you can have an outer lexical and an inner one and assign between the two:
my $foo = 42;
{
my $foo = $foo;
$foo += 42;
print "foo is $foo\n";
}
print "foo is $foo\n";
If you have a recent version of Perl, you don't actually need to access $fact within the subroutine because the __SUB__ pseudo-constant offers a reference to the current subroutine.
use 5.016;
my $fact = sub {
my $n = shift;
if ($n == 0) {
return 1;
}
return $n * __SUB__->($n-1);
};
Note that in the first example (where the $fact variable is used within the sub), a reference cycle is created, which might lead to Perl leaking memory over time. __SUB__ is a fairly clean way to resolve that issue. (Other solutions to the problem include the Y-combinator and reference weakening.)
Related
I am working on a factorial function in Perl.
The code below gives me the error Can't return outside a subroutine.
factorial {
my $n = $ARGV[0];
if( $n <= 1 ){
return 1; # ----- Error Here -----
}
else {
return $n * factorial($n - 1);
}
}
I believe my if statement is still inside the subroutine. What is causing the error?
Indirect method notation strikes again![1]
factorial { ... }
is being parsed as
(do { ... })->factorial
The problem is that you are missing the sub keyword at the start of the sub's declaration. Replace
factorial { ... }
with
sub factorial { ... }
Also, subroutine arguments are provided in #_, not #ARGV, so
my $n = $ARGV[0];
should be
my $n = $_[0];
-or-
my $n = shift;
-or-
my ($n) = #_;
Finally, using a recursive approach is very inefficient. Sub calls are rather expensive. The following is much faster:
sub factorial {
my $n = shift;
my $acc = 1;
$acc *= $_ for 2..$n;
return $acc;
}
It's existence causes many errors from being caught when they should be, as you can see in this magnificent example.
How do I pass a local variable to a Perl subroutine and modify it?
use strict;
use warnings;
sub modify_a
{
# ????
}
{
my $a = 5;
modify_a($a);
print "$a\n"; # want this to print 10
}
sub modify_a {
$_[0] *= 2;
}
The elements of #_ are aliases to the values passed in, so if you modify that directly, you'll change the caller's values. This can be useful sometimes, but is generally discouraged as it is usually a surprise to the caller.
A less magical approach is to pass a reference.
use strict;
use warnings;
sub modify_a
{
my ($a_ref) = #_;
$$a_ref = 10;
}
{
my $a = 5;
modify_a(\$a);
print "$a\n";
}
I have been using perl for some time now.
I want to know how I can run the following operation in perl:
subtract(40)(20)
To get the result:
20
I think I would have to look at custom parsing techniques for Perl.
This is what I am looking at right now:
Devel::Declare
Devel::CallParser
and
http://www.perl.com/pub/2012/10/an-overview-of-lexing-and-parsing.html
Now, I am not sure what to look for or what to do.
Any help on HOW to go about this, WHAT to read would be appreciated. Please be clear.
Thank you.
I recommend trying Parse::Keyword. Parse::Keyword is really great for parsing custom syntax, as it lets you call back various parts of the Perl parser, such as parse_listexpr, parse_block, parse_fullstmt, etc (see perlapi).
It has a drawback in that if you use those to parse expressions that close over variables, these are handled badly, but this can be worked around with PadWalker.
Parse::Keyword (including PadWalker trickery) is what Kavorka uses; and that does some pretty complex stuff! Early versions of p5-mop-redux used it too.
Anyway, here's a demonstration of how your weird function could be parsed...
use v5.14;
use strict;
use warnings;
# This is the package where we define the functions...
BEGIN {
package Math::Weird;
# Set up parsing for the functions
use Parse::Keyword {
add => \&_parser,
subtract => \&_parser,
multiply => \&_parser,
divide => \&_parser,
};
# This package is an exporter of course
use parent 'Exporter::Tiny';
our #EXPORT = qw( add subtract multiply divide );
# We'll need these things from PadWalker
use PadWalker qw( closed_over set_closed_over peek_my );
sub add {
my #numbers = _grab_args(#_);
my $sum = 0;
$sum += $_ for #numbers;
return $sum;
}
sub subtract {
my #numbers = _grab_args(#_);
my $diff = shift #numbers;
$diff -= $_ for #numbers;
return $diff;
}
sub multiply {
my #numbers = _grab_args(#_);
my $product = 1;
$product *= $_ for #numbers;
return $product;
}
sub divide {
my #numbers = _grab_args(#_);
my $quotient = shift #numbers;
$quotient /= $_ for #numbers;
return $quotient;
}
sub _parser {
lex_read_space;
my #args;
while (lex_peek eq '(')
{
# read "("
lex_read(1);
lex_read_space;
# read a term within the parentheses
push #args, parse_termexpr;
lex_read_space;
# read ")"
lex_peek eq ')' or die;
lex_read(1);
lex_read_space;
}
return sub { #args };
}
# In an ideal world _grab_args would be implemented like
# this:
#
# sub _grab_args { map scalar(&$_), #_ }
#
# But because of issues with Parse::Keyword, we need
# something slightly more complex...
#
sub _grab_args {
my $caller_vars = peek_my(2);
map {
my $code = $_;
my $closed_over = closed_over($code);
$closed_over->{$_} = $caller_vars->{$_} for keys %$closed_over;
set_closed_over($code, $closed_over);
scalar $code->();
} #_;
}
# We've defined a package inline. Mark it as loaded, so
# that we can `use` it below.
$INC{'Math/Weird.pm'} = __FILE__;
};
use Math::Weird qw( add subtract multiply );
say add(2)(3); # says 5
say subtract(40)(20); # says 20
say multiply( add(2)(3) )( subtract(40)(20) ); # says 100
If you can live with the additions of a sigil and an arrow, you could curry subtract as in
my $subtract = sub {
my($x) = #_;
sub { my($y) = #_; $x - $y };
};
Call it as in
my $result = $subtract->(40)(20);
If the arrow is acceptable but not the sigil, recast subtract as
sub subtract {
my($x) = #_;
sub { my($y) = #_; $x - $y };
};
Invocation in this case looks like
my $result = subtract(40)->(20);
Please don't tack on broken syntax extensions on your program to solve a solved problem.
What you want are closures, and a technique sometimes called currying.
Currying is the job of transforming a function that takes multiple arguments into a function that is invoked multiple times with one argument each. For example, consider
sub subtract {
my ($x, $y) = #_;
return $x - $y;
}
Now we can create a subroutine that already provides the first argument:
sub subtract1 { subtract(40, #_) }
Invoking subtract1(20) now evaluates to 20.
We can use anonymous subroutines instead, which makes this more flexible:
my $subtract = sub { subtract(40, #_) };
$subtract->(20);
We don't need that variable:
sub { subtract(40, #_) }->(20); # equivalent to subtract(40, 20)
We can write subtract in a way that does this directly:
sub subtract_curried {
my $x = shift;
# don't return the result, but a subroutine that calculates the result
return sub {
my $y = shift;
return $x - $y;
};
}
Now: subtract_curried(40)->(20) – notice the arrow in between, as we are dealing with a code reference (another name for anonymous subroutine, or closures).
This style of writing functions is much more common in functional languages like Haskell or OCaml where the syntax for this is prettier. It allows very flexible combinations of functions. If you are interested in this kind of programming in Perl, you might want to read Higher-Order Perl.
#Heartache: Please forget this challenge as it makes no sense for the parser and the user.
You can think of using fn[x][y] or fn{x}{y} which are valid syntax variants - i.e. you can stack [] and {} but not lists,
or fn(x,y) or fn(x)->(y) which do look nice, are also valid and meaningful syntax variants.
But fn(x)(y) will not know in which context the second list should be used.
For fn(x)(y) the common interpretation would be fn(x); (y) => (y). It returns the 2nd list after evaluating the first call.
You may create the source code filter:
package BracketFilter;
use Filter::Util::Call;
sub import {
filter_add(sub {
my $status;
s/\)\(/, /g if ($status = filter_read()) > 0;
return $status ;
});
}
1;
And use it:
#!/usr/bin/perl
use BracketFilter;
subtract(40)(20);
sub subtract {
return $_[0] - $_[1];
}
I created two subs one to do Fibonacci and the other to test even numbers. When I call it though it is saying my for loop in line 7 the sub Fibonacci is illegal why?
#!/usr/bin/perl
use strict;
use warnings;
my ($x,$y);
my $num = 0;
sub Fibs($start,$stop){
for ($start..$stop){
($x, $y) = ($y, $x+$y);
my $total += $y;
}
print "$total \n"
}
sub even($num){
if ($num % 2 == 0){
return $num;}
}
my $big_total = Fibs(even($num), 3999999)
Edited from suggestions below.
Clearly I am missing something. From feedback updated to new version.
#!/usr/bin/perl
use strict;
use warnings;
my ($x,$y);
my $num = 0;
sub Fibs{
my ($start, $stop) = #_ ;
for ($start..$stop){
my ($x, $y) = (0,2);
if ($x % 2 == 0){
($x, $y) = ($y, $x+$y);
my $total += $y;
}
}
my $big_total = Fibs(0, 3999999)
In addition to the missing opening braces, Perl doesn't support that kind of declaration for subroutine parameters.
Rather than
sub Fibs($start, $stop) {
...
}
you need to write something like:
sub Fibs {
my($start, $stop) = #_;
...
}
(Perl does have prototypes, but they're not really intended for declaring the types of parameters, and they don't provide names. See this article for a discussion.)
Other problems:
You should add
use strict;
use warnings;
You never use the $x and $y that you declare in the outer scope.
Your even function appears to be incomplete. It doesn't (explicitly) return a value if its argument is an odd number. What exactly is it intended to do?
the following code
#!/usr/bin/env perl
use strict;
use warnings;
my #foo = (0,1,2,3,4);
foreach my $i (#foo) {
sub printer {
my $blah = shift #_;
print "$blah-$i\n";
}
printer("test");
}
does not do what I would expect.
What exactly is happening?
(I would expect it to print out "test-0\ntest-1\ntest-2\ntest-3\ntest-4\n")
The problem is that the sub name {...} construct can not be nested like that in a for loop.
The reason is because sub name {...} really means BEGIN {*name = sub {...}} and begin blocks are executed as soon as they are parsed. So the compilation and variable binding of the subroutine happens at compile time, before the for loop ever gets a chance to run.
What you want to do is to create an anonymous subroutine, which will bind its variables at runtime:
#!/usr/bin/env perl
use strict;
use warnings;
my #foo = (0,1,2,3,4);
foreach my $i (#foo) {
my $printer = sub {
my $blah = shift #_;
print "$blah-$i\n";
};
$printer->("test");
}
which prints
test-0
test-1
test-2
test-3
test-4
Presumably in your real use case, these closures will be loaded into an array or hash so that they can be accessed later.
You can still use bareword identifiers with closures, but you need to do a little extra work to make sure the names are visible at compile time:
BEGIN {
for my $color (qw(red blue green)) {
no strict 'refs';
*$color = sub {"<font color='$color'>#_</font>"}
}
}
print "Throw the ", red 'ball'; # "Throw the <font color='red'>ball</font>"
Eric Strom's answer is correct, and probably what you wanted to see, but doesn't go into the details of the binding.
A brief note about lexical lifespan: lexicals are created at compile time and are actually available even before their scope is entered, as this example shows:
my $i;
BEGIN { $i = 42 }
print $i;
Thereafter, when they go out of scope, they become unavailable until the next time they are in scope:
print i();
{
my $i;
BEGIN { $i = 42 }
# in the scope of `my $i`, but doesn't actually
# refer to $i, so not a closure over it:
sub i { eval '$i' }
}
print i();
In your code, the closure is bound to the initial lexical $i at compile time.
However, foreach loops are a little odd; while the my $i actually creates a lexical, the foreach loop does not use it; instead it aliases it to one of the looped over values each iteration and then restores it to its original state after the loop. Your closure thus is the only thing referencing the original lexical $i.
A slight variation shows more complexity:
foreach (#foo) {
my $i = $_;
sub printer {
my $blah = shift #_;
print "$blah-$i\n";
}
printer("test");
}
Here, the original $i is created at compile time and the closure binds to that; the first iteration of the loop sets it, but the second iteration of the loop creates a new $i unassociated with the closure.