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

4

14

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?

Hulse answered 9/7, 2013 at 8:53 Comment(3)
what about sub other {do_some(@_);}Clercq
I only get the warning if I try to execute the module directly, but I don't get any warning if I just use the module in a script.Midtown
yes, this is solution, but in perldoc *other = \&do_some; is recommended for making subroutine aliases, and i was wondered when get this warningHulse
D
9
{
   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!

Dictator answered 9/7, 2013 at 11:41 Comment(1)
works great! Thank you. But I interchanged *other if 0; and *other = \&do_some, because warning was still there. Now its goneHulse
W
6

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.

Winton answered 9/7, 2013 at 9:2 Comment(0)
P
0

In later versions of Perl the no warnings pragma is insufficient to prevent the warning. Instead one has to write:

BEGIN {
  *bar = \&foo;
}

(And yes, no warnings is not needed.)

Order relative to the definition of foo does not matter; a subsequent sub foo will define bar as well, or calling bar without any definition for foo will report Undefined subroutine &main::bar

Petiole answered 17/8, 2022 at 3:6 Comment(0)
T
0

Keep it simple, keep it small.

If a warning like this is seen:

Name used only once: possible typo

Then mention the varname again, use just "our" like this:

our $someNiceName;
$someNiceName = "any XYZ etc pp";

If your script references and includes other scripts with:

require "otherScriptWithVarsAndDefinitions.cgi";

Then the var declaration is often only once in each script. Add a line like

our $someNiceName;

This will remove the warning and solves the problem.

Tutorial answered 12/5, 2023 at 16:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.