Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

question on declaring variables

by badbanana (Novice)
on Nov 22, 2018 at 11:54 UTC ( #1226176=perlquestion: print w/replies, xml ) Need Help??

badbanana has asked for the wisdom of the Perl Monks concerning the following question:

i have this two files below. the first one produces no errors but the second one produces the following errors:

Global symbol "$x" requires explicit package name (did you forget to declare "my $x"?) at ./two.pl line 6.
Global symbol "$y" requires explicit package name (did you forget to declare "my $y"?) at ./two.pl line 7.
Global symbol "$x" requires explicit package name (did you forget to declare "my $x"?) at ./two.pl line 10.
Global symbol "$y" requires explicit package name (did you forget to declare "my $y"?) at ./two.pl line 13.
Global symbol "$x" requires explicit package name (did you forget to declare "my $x"?) at ./two.pl line 15.
Global symbol "$y" requires explicit package name (did you forget to declare "my $y"?) at ./two.pl line 15.
Execution of ./two.pl aborted due to compilation errors.

this is file 1:
#!/usr/bin/perl use warnings; use strict; $a=0; chomp($a=<STDIN>); print $a, "\n";
and this is file 2:
#!/usr/bin/perl use warnings; use strict; $x=0; $y=0; print "enter first number "; chomp($x=<STDIN>); print "enter second number "; chomp($y=<STDIN>); print "Product ",$x*$y, "\n";
i can't seem to figure out what's causing the errors for file 2. the declaration is the same in both files.

Replies are listed 'Best First'.
Re: question on declaring variables
by toolic (Bishop) on Nov 22, 2018 at 12:03 UTC
    Yes, the declaration is the same for both files, but $a is a special variable, whereas $x and $y are not. You get the error messages because you correctly use strict:
    Because of their special use by sort(), the variables $a and $b are exempted from this check.
    You should avoid using $a and $b because they are special for the sort function. As the helpful message reports, you need to declare x and y with my.
      oh i see. thanks, got it!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://1226176]
Approved by toolic
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2021-11-28 21:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?