Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the point of `use vars` in this Perl subroutine?

Tags:

perl

In one of the chapters in Mastering Perl, brian d foy shows this snippet from List::Util:

sub reduce(&@) {
    my $code = shift;
    no strict "refs";
    return shift unless @_ > 1;
    use vars qw($a $b);
    my $caller = caller;
    local(*{$caller . "::a"}) = \my $a;
    local(*{$caller . "::b"}) = \my $b;
    $a = shift;
    foreach(@_) {
        $b = $_;
        $a = &{$code}();
    }
    $a;
}

I don't understand what's the point of the use vars qw($a $b) line. Even if I comment it, I get the same output & warnings.

like image 607
Geo Avatar asked Feb 14 '10 16:02

Geo


People also ask

What does @_ mean in Perl?

Using the Parameter Array (@_) Perl lets you pass any number of parameters to a function. The function decides which parameters to use and in what order.

How do we access the arguments inside a subroutine in Perl?

You can pass various arguments to a subroutine like you do in any other programming language and they can be acessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.

What is subroutine in Perl?

A Perl function or subroutine is a group of statements that together perform a specific task. In every programming language user want to reuse the code. So the user puts the section of code in function or subroutine so that there will be no need to write code again and again.

How do I return a value from a subroutine in Perl?

You can return a value from Perl subroutine as you do in any other programming language. If you are not returning a value from a subroutine then whatever calculation is last performed in a subroutine is automatically also the return value.


1 Answers

This is done because List::Util uses reduce() function internally.

In the abscence of use vars, the following warning is given when the function is used:

Name "List::MyUtil::a" used only once: possible typo at a.pl line 35.
Name "List::MyUtil::b" used only once: possible typo at a.pl line 35.

You can see this for yourself by running the following code:

use strict;
use warnings;

package List::MyUtil;

sub reduce (&@) {
   # INSERT THE TEXT FROM SUBROUTINE HERE - deleted to save space in the answer
}

sub x {
    return reduce(sub {$a+$b}, 1,2,3);
}

package main;
my $res = List::MyUtil::x();
print "$res\n";

And then running it again with use vars disabled.

like image 164
DVK Avatar answered Nov 16 '22 11:11

DVK