2

Why do I get the warning Name "main::USER_INPUT" used only once: possible typo when I run the following script?...

my $success_open = open USER_INPUT , '<:encoding(UTF-8)', $filehandle;

if(!$success_open)
{
    die "Failed to open: $filehandle. $!";
}

while(<USER_INPUT>)
{
    push @storage, $_;
}

close USER_INPUT;

Despite the warning, the script runs fine. It seems that I use USER_INPUT three times: once when I open it as a filehandle, once when I read from it, and once when I close it. Do open and close not count as usage of USER_INPUT? My guess is that warnings should count them. If it doesn't count them, then why?

I read several web pages about the once warning, and they give solutions to suppress the warning, but they do not seem to give enough information to understand why/how once occurs for my case:

How/Where can I find more info about how the once warning works? Is there a URL, Book, file, etc.? Maybe the code for once is in my Perl installation somewhere, but I do not know where. I've also skimmed through the following books (including their indices) and did not find any detailed info about once:

  • Learning Perl
  • Intermediate Perl
  • Mastering Perl
  • Programming Perl
  • Perl Cookbook
Arya
  • 566
  • 2
  • 9
  • 22
  • 3
    The code you posted doesn't produce the error you claim it does. It produces `Name "main::storage" used only once: possible typo at a.pl line 10.` and `@storage` is indeed used only once. – ikegami Aug 10 '18 at 23:35
  • 3
    ALWAYS use `use strict; use warnings qw( all );`. And don't use global vars for file handles; instead, use `open my $USER_INPUT, ...`, etc. – ikegami Aug 10 '18 at 23:37
  • 1
    Don't use bareword filehandles. Use lexical filehandles instead. – Matt Jacob Aug 10 '18 at 23:37
  • 1
    Also https://stackoverflow.com/questions/39958624/perl-name-mainin-used-only-once-but-it-is-actually-used – Matt Jacob Aug 10 '18 at 23:45
  • If it's not a duplicate (i.e. if you aren't using `use autodie;`), please fix your question so it actually demonstrates your problem and we'll reopen the Question. – ikegami Aug 11 '18 at 05:29
  • My question is a duplicate. I was using `autodie`. The code I used in my example is a snippet of a lengthier script. I excluded the other portions of my script (including the pragmas), because I incorrectly thought they were not pertinent. I realized that the snippet I used was incomplete because because @ikegami pointed out the different warning it produced. Rookie mistake I guess. So, lesson learned: One should use scalar filehandles instead of `bareword filehandles` (aka `package filehandles`?) or else `use autodie` may trigger a bug. – Arya Aug 11 '18 at 05:53
  • One should limit the scope of variables to where they are needed, autodie or not. – ikegami Aug 11 '18 at 05:58

0 Answers0