Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

uninitialized variable

by Fingo (Monk)
on Feb 28, 2001 at 03:55 UTC ( #61237=perlquestion: print w/replies, xml ) Need Help??

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

This is a subroutine from a program of mine and it's call. Why does -w give me an uninitialized value error, I defined it correctly. The program works right if I turn off -w.
#!/usr/bin/perl print CalcBalance(\"balance.log"); sub CalcBalance { my ($balance, @log); my $location = 0; #because my $location = shift(@ARGV) does not w +ok either. $location = shift(@ARGV); # the following is not needed # open (RBALANCE, $location); # @log = <RBALANCE>; # $balance = $log[-1]; # close (RBALANCE); # if (@ARGV && $ARGV[0] != 0) { # we check to see if there is a +nother # # argument (the amount to change) a +nd # # it is not 0. # # my $toChange = shift (@ARGV); # we only declare this if another # # argument exists to make the test # # above work. # $balance += $toChange; # open (WBALANCE, ">>$location"); # print WBALANCE $balance; # close (WBALANCE); # } }


Replies are listed 'Best First'.
Re: uninitialized variable
by bbfu (Curate) on Feb 28, 2001 at 04:01 UTC

    In a subroutine, you need to use @_ not @ARGV. @ARGV is only for parameters passed into the script when invoking it (ie, from the command-line). @_ is where subroutine parameters are passed.

    So change all the lines that say shift(@ARGV) to shift(@_) and it should be fine.

    Seasons don't fear The Reaper.
    Nor do the wind, the sun, and the rain.
    We can be like they are.

Re: uninitialized variable
by arturo (Vicar) on Feb 28, 2001 at 04:04 UTC
    $location = shift(@ARGV); will set $location to undef if no arguments have been passed to the script (@ARGV refers only to the command line, as bbfu points out). That's why you're getting the warning.

    For cases like these, you can either do:

    my $location = shift @ARGV or die "usage: $0 [filename]\n";

    or, if you want a default,

    my $location = shift || 'default value';

    Minor amplification shift called without an explicit argument will return the next element of @ARGV if it is called outside a subroutine, and returns the next element of @_ if called within a subroutine.


    Philosophy can be made out of anything. Or less -- Jerry A. Fodor

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://61237]
Approved by root
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (9)
As of 2020-10-20 15:25 GMT
Find Nodes?
    Voting Booth?
    My favourite web site is:

    Results (210 votes). Check out past polls.