Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "... used only once: possible typo" warning when aliasing subroutines

Tags:

perl

I have some module, and want to make alias for some sub. Here is the code:

#!/usr/bin/perl

package MySub;

use strict;
use warnings;

sub new {
    my $class = shift;
    my $params = shift;
    my $self = {};
    bless( $self, $class );
    return $self;
}

sub do_some {
    my $self = shift;
    print "Do something!";
    return 1;
}

*other = \&do_some;

1;

It works, but it produces a compile warning

Name "MySub::other" used only once: possible typo at /tmp/MySub.pm line 23.

I know that I can just type no warnings 'once';, but is this the only solution? Why is Perl warning me? What am I doing wrong?

like image 995
Suic Avatar asked Jul 09 '13 08:07

Suic


2 Answers

{
   no warnings 'once';
   *other = \&do_some;
}

or

*other = \&do_some;
*other if 0;  # Prevent spurious warning

I prefer the latter. For starters, it will only disable the instance of the warning you wish to disable. Also, if you remove one of the lines and forget to remove the other, the other will start warning. Perfect!

like image 72
ikegami Avatar answered Oct 19 '22 01:10

ikegami


You should type a bit more:

{   no warnings 'once';
    *other = \&do_some;
}

This way, the effect of no warnings is reduced only to the problematic line.

like image 36
choroba Avatar answered Oct 19 '22 00:10

choroba