In one of my modules I have a statement like this:
Perl warns Name "MyApp::once" used only once: possibly typo. While it is true that this happened to be the only usage of %Pck::v in my program at the time, I wonder what is the best way to suppress this warning. Clearly I can't use use vars nor our here. Sure I can suppress the warnings with no warnings in the surrounding block. Any other suggestion?$MyApp::once{x} ||= 1;
OK, maybe we have a XY problem here, so this is how I stumbled into this problem (maybe you have a better suggestion, but I still would be interested in an answer to my original question as well): I have some functions, which gets executed often, but are supposed to log some information only during the first time they are executed:
In languages such as C++, I would use a local static for this purpose:sub f { ... log('some information'); # but should be called only the first time. ... }
We don't have local statics in Perl, so one possibility would be to use a 'my' variable on file scope:static LogRetType const once=log('some information');
But I neither like the fact that the definition of $once1 is not logically close to its (only) usage, but also that I need to invent a new variable every time I do this in my package. So I thought that I would instead have a single variable of this kind for my whole application, but use a hash for this purpose, and the file name and line number as a key:my $once1=0; sub f { ... $once1 ||= (log('some information'),1); ... }
This works, as long as I have two or more lines of this type in my package; but if there is only one occurence, I get the aforementioned warning.sub f { ... $MyApp{+__FILE__.' '.__LINE__} ||= (log('some information'),1); ... }
In reply to Why do I get a "used only once" warning here? by rovf
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |