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?

doubleDown
  • 8,048
  • 1
  • 32
  • 48
Suic
  • 2,441
  • 1
  • 17
  • 30
  • what about `sub other {do_some(@_);}` –  Jul 09 '13 at 08:58
  • 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. – doubleDown Jul 09 '13 at 09:08
  • 1
    yes, this is solution, but in perldoc `*other = \&do_some;` is recommended for making subroutine aliases, and i was wondered when get this warning – Suic Jul 09 '13 at 09:09

4 Answers4

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!

ikegami
  • 367,544
  • 15
  • 269
  • 518
  • works great! Thank you. But I interchanged `*other if 0;` and `*other = \&do_some`, because warning was still there. Now its gone – Suic Jul 09 '13 at 12:18
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.

choroba
  • 231,213
  • 25
  • 204
  • 289
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

Martin Kealey
  • 546
  • 2
  • 11
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.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77