global symbol requires explicit package name.Error - perl

If i give the variables as global it works fine. What is wrong with this code?
sub Multiply {
$res = $a* $b;
return ( $a, $b, $res);
}
main:
my $a =3;
my $b =4;
my $res;
( $a, $b, $res) = Multiply();
print ("Input1 = $a\nInput2 = $b\nResult = $res");

The most important wrong thing is that you don't declare variables and don't have
use warnings;
use strict;
Also, using $a and $b is perilous since they are globals meant for sort.
The my variables $a, $b, $res are lexical but the ones in the sub are yet other, global variables; this is because the sub is defined before the lexicals are declared. They are never initialized, so their undefs overwrite lexicals on return. With use warnings; added
Use of uninitialized value $b in multiplication (*) at .. [in sub]
Use of uninitialized value $a in multiplication (*) at .. [in sub]
Use of uninitialized value $a in concatenation (.) or string at .. [in print]
Use of uninitialized value $b in concatenation (.) or string at .. [in print]
The global $res in the sub gets initialized to 0 and its return overwrites the lexical one.
If you were to put the code for the sub at the end it would "work," since lexicals get declared before the sub gets compiled so the sub sees them and uses them. But then again, if lexicals are in a "dynamic" scope that wouldn't work either; see this post. And altogether, using globals in a sub is not good.
Just declare variables in the subroutine and pass to it what it needs.
Then they exist only in the sub, also masking possible such names from outside scope. The sub has a well defined interface, returns values (scalars) which you assign as needed, and all is clear.
See Private Variables via my() in perlsub
Update
The title hints at use strict; being in place, and a comment states that. Then the question would be about declaration of variables.
The strict pragma requires, among a few other things, that all variables be declared or fully qualified.
The $res in the sub isn't declared, thus the compilation fails; the $a and $b exist as globals (but for use with sort – don't use them for convenience). A declared variable is seen in included scopes but with functions this isn't quite so simple and you want to declare all variables inside a function.
Global-like variables declared with our are OK but their use brings about other issues. While globals do get used occasionally they are very rarely needed and are best avoided, since their use can ruin clean scoping which is one of critical principles in programming.
A useful reference is perldiag, which explains error messages. Or, use diagnostics in debugging runs, or better yet use splain or run the code with perl -Mdiagnostics ...

Related

How to access a sub through symbol table for main:: and name of sub in a scalar variable

Suppose I have a function foo (or ::foo, or main::foo if you prefer), and I define
use strict;
my $sub_name = 'foo';
I want to invoke foo indirectly, as "the function whose name is stored in $sub_name". (For the sake of this example, assume that the invocation should pass the list 1, 2, 3 as arguments.)
I know that there's a way to do this by working with the symbol table for main:: directly, treating it like a hash-like data structure.
This symbol-table incantation is what I'm looking for.
I've done this sort of thing many times before, but I have not programmed Perl in many years, and I no longer remember the incantation.
(I'd prefer to do this without having to resort to no strict, but no biggie if that's not possible.)
I'd simply use a symbolic reference.
my $sub = \&$qualified_sub_name; # \&$symbol is except from strict 'refs'.
$sub->()
But you requested that we avoid using symbolic reference. That's way too complex. (It's also might not handle weird but legit misuse of colons.)
my $pkg = \%::;
my $sub_name = $qualified_sub_name;
$pkg = $pkg->{$1} while $sub_name =~ s/^(.*?::)//sg;
my $sub = $pkg->{$sub_name};
$sub = *{ $pkg->{$sub_name} }{CODE}
if ref(\$sub) eq 'GLOB'; # Skip if glob optimized away.
$sub->()
You can use can:
my $sub_name = 'foo';
my $coderef = main->can($sub_name);
$coderef->(#args);
As others have mentioned, you should note that this can return also methods like "can" or "isa".
Also, if $sub_name contains Some::Module::subname, this will also be called.
If you're not sure what's in $sub_name, you probably want a different approach.
Use this only if you have control over $sub_name and it can contain only expected values. (I assumed this, that's why I wrote this answer.)

How to get the global variable value in Perl?

Trying to understand scope resolution operator.
$a = 5;
foo();
print "Out a = $a\n";
sub foo() {
local $a = 10;
bar();
}
sub bar() {
print "Inside a = $a\n";
print "Global a = $::a\n";
}
Output from this program is :
Inside a = 10
Global a = 10
Out a = 5
I would have expected value of '$::a' to come out as '5' instead of 10. I thought that is what scope resolution operator do. Getting scoped values. In this case, no scope is given, so global value. Please correct me if there is any tweak.
What should I write to get the global value of 'a' inside bar subroutine?
You are misunderstanding ::. Perl doesn't really have global variables (leaving aside certain special identifier names); it has package variables. That is, every global variable belongs to a package. If your code has no package statement, that package is main, so $a is the same as $main::a. And having nothing before the :: is shorthand for main, so $::a is also $main::a.
If you do have a package declaration, package variables used within its scope will be contained in that package unless qualified with ::.
local gives a package variable or hash or array element a temporary value and saves the previous value to be restored when the innermost scope is left.
There is no way to access that saved value from within the scope of the local.
The opposite of global/package variables are lexical variables. You almost always will want to use lexical variables (declared with my), not package variables. Even when you do use package variables, you will hardly ever want to change their value with local. So a good case for using local is going to be truly rare.
Well, first off - don't use $a - single letter variable names are generally nasty, and that goes double for when it's used by sort.
Secondly local doesn't do what you think it does. It even says in the man page:
You really probably want to be using my instead, because local isn't what most people think of as "local". See Private Variables via my() in perlsub for details.
A local modifies the listed variables to be local to the enclosing block, file, or eval. If more than one value is listed, the list must be placed in parentheses. See Temporary Values via local() in perlsub for details, including issues with tied arrays and hashes.
So you probably want to use my, but... actually, more likely, you probably just want to not do that, and don't use globals at all.
#!/usr/bin/env perl
use strict;
use warnings;
our $number = 5;
foo();
print "Out number = $number\n";
sub foo {
my $number = 10;
print "Inside foo: $number\n";
print "Global foo $::number\n";
bar();
}
sub bar {
print "Inside bar = $number\n";
print "Global $::number\n";
}
As you can see - $number is lexically scoped to be "within foo" and doesn't persist into b.
Inside foo: 10
Global foo = 5
Inside a = 5
Global a = 5
Out number = 5
Thirdly - don't use prototypes on your subs. They don't do what you think they do.

Why declare Perl variable with "my" at file scope?

I'm learning Perl and trying to understand variable scope. I understand that my $name = 'Bob'; will declare a local variable inside a sub, but why would you use the my keyword at the global scope? Is it just a good habit so you can safely move the code into a sub?
I see lots of example scripts that do this, and I wonder why. Even with use strict, it doesn't complain when I remove the my. I've tried comparing behaviour with and without it, and I can't see any difference.
Here's one example that does this:
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
my $dbfile = "sample.db";
my $dsn = "dbi:SQLite:dbname=$dbfile";
my $user = "";
my $password = "";
my $dbh = DBI->connect($dsn, $user, $password, {
PrintError => 0,
RaiseError => 1,
AutoCommit => 1,
FetchHashKeyName => 'NAME_lc',
});
# ...
$dbh->disconnect;
Update
It seems I was unlucky when I tested this behaviour. Here's the script I tested with:
use strict;
my $a = 5;
$b = 6;
sub print_stuff() {
print $a, $b, "\n"; # prints 56
$a = 55;
$b = 66;
}
print_stuff();
print $a, $b, "\n"; # prints 5566
As I learned from some of the answers here, $a and $b are special variables that are already declared, so the compiler doesn't complain. If I change the $b to $c in that script, then it complains.
As for why to use my $foo at the global scope, it seems like the file scope may not actually be the global scope.
The addition of my was about the best thing that ever happened to Perl and the problem it solved was typos.
Say you have a variable $variable. You do some assignments and comparisons on this variable.
$variable = 5;
# intervening assignments and calculations...
if ( $varable + 20 > 25 ) # don't use magic numbers in real code
{
# do one thing
}
else
{
# do something else
}
Do you see the subtle bug in the above code that happens if you don't use strict; and require variables be declared with my? The # do one thing case will never happen. I encountered this several times in production code I had to maintain.
A few points:
strict demands that all variables be declared with a my (or state) or installed into the package--declared with an our statement or a use vars pragma (archaic), or inserted into the symbol table at compile time.
They are that file's variables. They remain of no concern and no use to any module required during the use of that file.
They can be used across packages (although that's a less good reason.)
Lexical variables don't have any of the magic that the only alternative does. You can't "push" and "pop" a lexical variable as you change scope, as you can with any package variable. No magic means faster and plainer handling.
Laziness. It's just easier to declare a my with no brackets as opposed to concentrating its scope by specific bracketing.
{ my $visible_in_this_scope_only;
...
sub bananas {
...
my $bananas = $visible_in_this_scope_only + 3;
...
}
} # End $visible_in_this_scope_only
(Note on the syntax: in my code, I never use a bare brace. It will always tell you, either before (standard loops) or after what the scope is for, even if it would have been "obvious".
It's just good practice. As a personal rule, I try to keep variables in the smallest scope possible. If a line of code can't see a variable, then it can't mess with it in unexpected ways.
I'm surprised that you found that the script worked under use strict without the my, though. That's generally not allowed:
$ perl -E 'use strict; $db = "foo"; say $db'
Global symbol "$db" requires explicit package name at -e line 1.
Global symbol "$db" requires explicit package name at -e line 1.
Execution of -e aborted due to compilation errors.
$ perl -E 'use strict; my $db = "foo"; say $db'
foo
Variables $a and $b are exempt:
$ perl -E 'use strict; $b = "foo"; say $b'
foo
But I don't know how you would make the code you posted work with strict and a missing my.
A sub controls/limits the scope of variables between the braces {} that define its operations. Of course many variables exist outside of a particular function and using lexical my for "global" variables can give you more control over how "dynamic" their behavior is inside your application. The Private Variables via my() section of perlodocperlsub discusses reasons for doing this pretty thoroughly.
I'm going to quote myself from elsewhere which is not the best thing to do on SO but here goes:
The classic perlmonks node - Variable Scoping in Perl: the
basics - is a frequently
consulted reference :-)
As I noted in a comment, Bruce Gray's talk at YAPC::NA 2012 - The why of my() is a good story about how a pretty expert perl programmer wrapped his head around perl and namespaces.
I've heard people explain my as Perl's equivalent to Javascript's var - it's practically necessary but, Perl being perl, things will work without it if you insist or take pains to make it do that.
ps: Actually with Javascript, I guess functions are used to control "scope" in a way that is analagous to your description of using my in sub's.

How to check if variable is declared in perl?

I am using use strict; in perl and with that I use the following statement.
unless(defined($x)){
print "Not defined";
}
Where $x is not declared anywhere. So I expect it to print "Not defined" but it returns an error
Global symbol "$x" requires explicit package name at *********** in line 15.
The strict pragma has three parts: strict references, strict variables, and strict subs. The one you're running into is
strict vars
This generates a compile-time error if you access a variable that wasn't declared via our or use vars, localized via my, or wasn't fully qualified. Because this is to avoid variable suicide problems and subtle dynamic scoping issues, a merely local variable isn't good enough.
Because it generates compile-time errors, your non-BEGIN code won't even have a chance to run. You can temporarily allow non-strict variables inside a block as in
{
no strict 'vars';
print "Not defined!\n" unless defined $x;
}
but note that Perl's defined operator tells you whether a value is defined, not whether a variable has been declared.
Tell us more about your application, and we can give you better advice about how to handle it.
You can't even refer to a variable unless it's declared. When you ask
defined( $x ) ?
the compiler is going to complain: I don't know this what you're asking about, how am I supposed to tell it is defined? It has no point of reference for that variable, since you've indicated you do not want variables auto-created by name.
If strict 'vars' was not on--which it is by default when you use strict--then it would create an entry in the package symbol table for 'x'.
Interestingly enough is that without strict 'refs' it is also easy to check if a variable is in the package symbol table.
defined( *{ __PACKAGE__ . '::x' }{SCALAR} )
Since there is no way to auto-create a lexical ("my variables"), there is also not a standard way to check to see if lexicals are declared. Lexical variables are stored in the "pad". But there is a module PadWalker that can help.
In order to check the current level, you could get a hash of the pad, and then check whether or not it exists in the current pad. You could also loop back up through the stack (the integer argument works something like caller) to find where the most recent x was.
my $h = peek_my (0);
exists $h->{x};
I think you are mixing 'defined' and 'declared' concepts.
Your are asking for 'How to check if variable is declared in perl' but then you are checking if a variable is defined. These are two different concepts.
In perl if you use 'use strict' you are automatically checking for any variable not declared (using my, local or our). Once you have a variable declared, you can test if it is defined (have a value assigned).
So in your test, you are missing a prior declaration before testing for defineness
use strict;
my $x; # you are missing this part
[...] | # code
# your test for define
print defined $x? "defined\n" : "not defined\n";
Please be aware the testing for only $x is incorrect for your purpose:
my ($x,$y, $z);
$w; # not declared (use strict will catch it and die)
$x = 0; # declared and defined BUT if you make a logic test like 'if ($x) {}' then it will be FALSE, so don't confuse testing for **'$x'** and testing for **'defined $x'**
$y = undef; # declared but not defined
$z = 1; # declared, defined, and logial test TRUE
Finally the answer of xenorraticide seems faulty to me: he suggest 'unless $x' that is not correct for testing if defined as I said before. He also suggest 'unless exists $x', that is wrong for testing scalars. 'exists' test is only for hashes keys (and deprecated for arrays).
Hope this helps.
#
print "Not defined" if !defined($x);
result will be
Not defined
#
use strict;
print "Not defined" if !defined($x);
will generate error as in your question.
Look to: http://perldoc.perl.org/strict.html, where described how you can import only required restrictions. (However use strict 'vars' is very good idea :) )
Normally this kind of code should not be required for a serious program, but still why not just for fun: (assuming use strict)
print "Not defined\n" unless eval 'ref(\$x)';
#!/usr/bin/perl -l
use strict;
# if string below commented out, prints 'lol' , if the string enabled, prints 'eeeeeeeee'
#my $lol = 'eeeeeeeeeee' ;
# no errors or warnings at any case, despite of 'strict'
our $lol = eval {$lol} || 'lol' ;
print $lol;
my solution is
#!/usr/bin/perl -l
use strict;
# if string below commented out, prints 'lol' , if the string enabled, prints 'eeeeeeeee'
#my $lol = 'eeeeeeeeeee' ;
# no errors or warnings at any case, despite of 'strict'
our $lol = eval {$lol} || 'lol' ;
print $lol;
You can use unless, like this:
use 'strict';
my $var = 'defined';
unless (defined($var)) {
print "not defined\n";
}
$var = undef;
unless (defined($var)) {
print "not defined\n";
}
The first print will not print anything, the second one will since $var has been made undef.

What is the difference between 'my' and 'our' in Perl?

I know what my is in Perl. It defines a variable that exists only in the scope of the block in which it is defined. What does our do?
How does our differ from my?
How does our differ from my and what does our do?
In Summary:
Available since Perl 5, my is a way to declare non-package variables, that are:
private
new
non-global
separate from any package, so that the variable cannot be accessed in the form of $package_name::variable.
On the other hand, our variables are package variables, and thus automatically:
global variables
definitely not private
not necessarily new
can be accessed outside the package (or lexical scope) with the
qualified namespace, as $package_name::variable.
Declaring a variable with our allows you to predeclare variables in order to use them under use strict without getting typo warnings or compile-time errors. Since Perl 5.6, it has replaced the obsolete use vars, which was only file-scoped, and not lexically scoped as is our.
For example, the formal, qualified name for variable $x inside package main is $main::x. Declaring our $x allows you to use the bare $x variable without penalty (i.e., without a resulting error), in the scope of the declaration, when the script uses use strict or use strict "vars". The scope might be one, or two, or more packages, or one small block.
The PerlMonks and PerlDoc links from cartman and Olafur are a great reference - below is my crack at a summary:
my variables are lexically scoped within a single block defined by {} or within the same file if not in {}s. They are not accessible from packages/subroutines defined outside of the same lexical scope / block.
our variables are scoped within a package/file and accessible from any code that use or require that package/file - name conflicts are resolved between packages by prepending the appropriate namespace.
Just to round it out, local variables are "dynamically" scoped, differing from my variables in that they are also accessible from subroutines called within the same block.
An example:
use strict;
for (1 .. 2){
# Both variables are lexically scoped to the block.
our ($o); # Belongs to 'main' package.
my ($m); # Does not belong to a package.
# The variables differ with respect to newness.
$o ++;
$m ++;
print __PACKAGE__, " >> o=$o m=$m\n"; # $m is always 1.
# The package has changed, but we still have direct,
# unqualified access to both variables, because the
# lexical scope has not changed.
package Fubb;
print __PACKAGE__, " >> o=$o m=$m\n";
}
# The our() and my() variables differ with respect to privacy.
# We can still access the variable declared with our(), provided
# that we fully qualify its name, but the variable declared
# with my() is unavailable.
print __PACKAGE__, " >> main::o=$main::o\n"; # 2
print __PACKAGE__, " >> main::m=$main::m\n"; # Undefined.
# Attempts to access the variables directly won't compile.
# print __PACKAGE__, " >> o=$o\n";
# print __PACKAGE__, " >> m=$m\n";
# Variables declared with use vars() are like those declared
# with our(): belong to a package; not private; and not new.
# However, their scoping is package-based rather than lexical.
for (1 .. 9){
use vars qw($uv);
$uv ++;
}
# Even though we are outside the lexical scope where the
# use vars() variable was declared, we have direct access
# because the package has not changed.
print __PACKAGE__, " >> uv=$uv\n";
# And we can access it from another package.
package Bubb;
print __PACKAGE__, " >> main::uv=$main::uv\n";
Coping with Scoping is a good overview of Perl scoping rules. It's old enough that our is not discussed in the body of the text. It is addressed in the Notes section at the end.
The article talks about package variables and dynamic scope and how that differs from lexical variables and lexical scope.
The perldoc has a good definition of our.
Unlike my, which both allocates storage for a variable and associates a simple name with that storage for use within the current scope, our associates a simple name with a package variable in the current package, for use within the current scope. In other words, our has the same scoping rules as my, but does not necessarily create a variable.
my is used for local variables, whereas our is used for global variables.
More reading over at Variable Scoping in Perl: the basics.
I ever met some pitfalls about lexical declarations in Perl that messed me up, which are also related to this question, so I just add my summary here:
1. Definition or declaration?
local $var = 42;
print "var: $var\n";
The output is var: 42. However we couldn't tell if local $var = 42; is a definition or declaration. But how about this:
use strict;
use warnings;
local $var = 42;
print "var: $var\n";
The second program will throw an error:
Global symbol "$var" requires explicit package name.
$var is not defined, which means local $var; is just a declaration! Before using local to declare a variable, make sure that it is defined as a global variable previously.
But why this won't fail?
use strict;
use warnings;
local $a = 42;
print "var: $a\n";
The output is: var: 42.
That's because $a, as well as $b, is a global variable pre-defined in Perl. Remember the sort function?
2. Lexical or global?
I was a C programmer before starting using Perl, so the concept of lexical and global variables seems straightforward to me: it just corresponds to auto and external variables in C. But there're small differences:
In C, an external variable is a variable defined outside any function block. On the other hand, an automatic variable is a variable defined inside a function block. Like this:
int global;
int main(void) {
int local;
}
While in Perl, things are subtle:
sub main {
$var = 42;
}
&main;
print "var: $var\n";
The output is var: 42. $var is a global variable even if it's defined in a function block! Actually in Perl, any variable is declared as global by default.
The lesson is to always add use strict; use warnings; at the beginning of a Perl program, which will force the programmer to declare the lexical variable explicitly, so that we don't get messed up by some mistakes taken for granted.
This is only somewhat related to the question, but I've just discovered a (to me) obscure bit of perl syntax that you can use with "our" (package) variables that you can't use with "my" (local) variables.
#!/usr/bin/perl
our $foo = "BAR";
print $foo . "\n";
${"foo"} = "BAZ";
print $foo . "\n";
Output:
BAR
BAZ
This won't work if you change 'our' to 'my'.
print "package is: " . __PACKAGE__ . "\n";
our $test = 1;
print "trying to print global var from main package: $test\n";
package Changed;
{
my $test = 10;
my $test1 = 11;
print "trying to print local vars from a closed block: $test, $test1\n";
}
&Check_global;
sub Check_global {
print "trying to print global var from a function: $test\n";
}
print "package is: " . __PACKAGE__ . "\n";
print "trying to print global var outside the func and from \"Changed\" package: $test\n";
print "trying to print local var outside the block $test1\n";
Will Output this:
package is: main
trying to print global var from main package: 1
trying to print local vars from a closed block: 10, 11
trying to print global var from a function: 1
package is: Changed
trying to print global var outside the func and from "Changed" package: 1
trying to print local var outside the block
In case using "use strict" will get this failure while attempting to run the script:
Global symbol "$test1" requires explicit package name at ./check_global.pl line 24.
Execution of ./check_global.pl aborted due to compilation errors.
Just try to use the following program :
#!/usr/local/bin/perl
use feature ':5.10';
#use warnings;
package a;
{
my $b = 100;
our $a = 10;
print "$a \n";
print "$b \n";
}
package b;
#my $b = 200;
#our $a = 20 ;
print "in package b value of my b $a::b \n";
print "in package b value of our a $a::a \n";
Let us think what an interpreter actually is: it's a piece of code that stores values in memory and lets the instructions in a program that it interprets access those values by their names, which are specified inside these instructions. So, the big job of an interpreter is to shape the rules of how we should use the names in those instructions to access the values that the interpreter stores.
On encountering "my", the interpreter creates a lexical variable: a named value that the interpreter can access only while it executes a block, and only from within that syntactic block. On encountering "our", the interpreter makes a lexical alias of a package variable: it binds a name, which the interpreter is supposed from then on to process as a lexical variable's name, until the block is finished, to the value of the package variable with the same name.
The effect is that you can then pretend that you're using a lexical variable and bypass the rules of 'use strict' on full qualification of package variables. Since the interpreter automatically creates package variables when they are first used, the side effect of using "our" may also be that the interpreter creates a package variable as well. In this case, two things are created: a package variable, which the interpreter can access from everywhere, provided it's properly designated as requested by 'use strict' (prepended with the name of its package and two colons), and its lexical alias.
Sources:
http://perldoc.perl.org/functions/our.html
http://perldoc.perl.org/perlsub.html#Private-Variables-via-my()
#!/usr/bin/perl -l
use strict;
# if string below commented out, prints 'lol' , if the string enabled, prints 'eeeeeeeee'
#my $lol = 'eeeeeeeeeee' ;
# no errors or warnings at any case, despite of 'strict'
our $lol = eval {$lol} || 'lol' ;
print $lol;