Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

usage of "my" keyword

by ravi45722 (Pilgrim)
on Aug 10, 2015 at 08:55 UTC ( [id://1137973]=perlquestion: print w/replies, xml ) Need Help??

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

Here cant i declare a variabe without using my keyword.
use strict; use warnings; my $number=8; my $i=0; #if i remove my keyword it gives error for($i=0;$i<20;$i++) { print "present value of the number is:"; print $number++; print "\n"; }

Error: Global symbol "$i" requires explicit package name at for.pl line 6.

If I use my keyword the scope of that variable is available in other functions also. But i dont need that. How to declare local variables??

How to merge these three lines

print "present value of the number is:"; print $number++; print "\n";

Replies are listed 'Best First'.
Re: usage of "my" keyword
by marto (Cardinal) on Aug 10, 2015 at 09:10 UTC

    You have use strict; so you must declare variables or the error you see will be thrown. If you've copied/paste this without understanding I suggest you read and understand strict. An alternative would be to declare $i within the for loop.

    "How to merge these three lines"

    One way to write this:

    use strict; use warnings; my $number=8; for( my $i=0; $i<20; $i++ ){ print "present value of the number is: $number\n"; $number++; }

    If you are new to perl the following links will likely be of interest:

      Here if i use my keyword for number its scope is also available in other functions. I want to restrict the scope of number. Thanks for reply
        No, if you declare $i inside the for loop the way marto has shown, the scope of $i will be only the for loop itself, not outside that block. Consider this example:
        $ perl -E 'for( my $i=0; $i<10; $i++ ){say "Inside loop: $i";} say "Ou +tside loop: $i";' Inside loop: 0 Inside loop: 1 Inside loop: 2 Inside loop: 3 Inside loop: 4 Inside loop: 5 Inside loop: 6 Inside loop: 7 Inside loop: 8 Inside loop: 9 Outside loop:
        You can see that the value of $i is not defined outside the loop. And if I add the warnings, I get:
        ... Inside loop: 9 Use of uninitialized value $i in concatenation (.) or string at -e lin +e 1. Outside loop:
        I want to restrict the scope of number.

        It's not clear to me, but it seems possible you're actually asking "I want to restrict the scope of the $number scalar." If that's the case, then one way is to establish an independent scope  { ... } for the variable:

        c:\@Work\Perl\monks>perl -wMstrict -le "my $number = 42; print '$number before independent scope == ', $number; ;; { my $number = 8; print '$number in independent scope == ', $number++ for 1 .. 5; } ;; print '$number after independent scope == ', $number; " $number before independent scope == 42 $number in independent scope == 8 $number in independent scope == 9 $number in independent scope == 10 $number in independent scope == 11 $number in independent scope == 12 $number after independent scope == 42

        Update: Discussions of scoping can be found throughout perlsyn and among the Tutorials in the Variables and Scoping section.


        Give a man a fish:  <%-(-(-(-<

        Here if i use my keyword for number its scope is also available in other functions. I want to restrict the scope of number.

        What other functions???

Re: usage of "my" keyword
by Athanasius (Archbishop) on Aug 10, 2015 at 09:11 UTC

      But since $i is not used:

      use strict; use warnings; my $number = 8; for (1 .. 20) { print "present value of the number is:", $number++, "\n"; } # or print "present value of the number is:", $number++, "\n" for 1 .. 20;

      make the number of iterations clearer and make it clear that the value of the count is unimportant.

      Premature optimization is the root of all job security

      More merging ...

      use 5.10.0; use warnings; my $number = 8; say "Present value of number is: ", $number++ for 0 .. 19;

      Enjoy, Have FUN! H.Merijn
Re: usage of "my" keyword
by poj (Abbot) on Aug 10, 2015 at 09:18 UTC
    Alternatively
    use strict; use warnings; my $number=8; for ($number..$number+19){ print "present value of the number is: $_ \n"; }
    poj
Re: usage of "my" keyword
by mendeepak (Scribe) on Aug 10, 2015 at 09:14 UTC

    If I am getting you right, you are not able to declare a variable without "my" in this code, That is because you are under strict pragma.
    Your first line of code
     use strict;
    enforces that the variables are declared properly, for more detailed reading please check perl docs perl docs

    For your second question please see perl docs or perl maven

    Life is a Climb, But view is Great...
    Deepak
Re: usage of "my" keyword (quibble re clarity)
by ww (Archbishop) on Aug 12, 2015 at 19:38 UTC

    Precision in language is crucial to writing your code. In this case, you're saying a present value is that value, post-incremented. Strictly speaking, that's true, but writing the code in this fashion is apt to trip the unwary -- author included:

    #!/usr/bin/perl =w use strict; #1137973 my $number=8; for(my $i=0; $i<3; $i++) { print "present value of \$i is $i and the number is: $number \n"; print " now printing \$number++: " . $number++ . "\n"; # NOTE O +UTPUT! print "!! NOW, NOT EARLIER the post-increment occurs AFTER Ln 10\ +n"; print " and after post-increment, \$i is STILL $i but number +is: $number\n\-----------\n"; } =head present value of $i is 0 and the number is: 8 now printing $number++: 8 # ie, unchanged! !! NOW, NOT EARLIER the post-increment occurs AFTER Ln 10 and after post-increment, $i is STILL 0 but number is: 9 ----------- present value of $i is 1 and the number is: 9 now printing $number++: 9 !! NOW, NOT EARLIER the post-increment occurs AFTER Ln 10 and after post-increment, $i is STILL 1 but number is: 10 ----------- present value of $i is 2 and the number is: 10 now printing $number++: 10 !! NOW, NOT EARLIER the post-increment occurs AFTER Ln 10 and after post-increment, $i is STILL 2 but number is: 11 ----------- =cut

    You're cheese-paring the size of your script by a few bytes at the expense of clarity; better to post-increment in a standalone line of code -- for clarity.

    UPDATE: ... or, as Athanasius pointed out in a message, a (standalone) pre-increment (++$number)could also be used effectively ... but that would REALLY require precise language... as in something like "the next number is: " or maybe "oops, off by one."

      I read all the manuals above suggested. But i have a small doubt

      #!/usr/bin/perl use strict; # my $row; . . for $row ($min..$max) { if($data == $required) { last; } } print "Data presented in:: $row \n";

      Here i am declaring the $row above the for loop. But the $row loosing its scope after the for loop. As per documents the scope of my variable does not lose.

      if i dont want to loose that variable scope & also i want to use strict then how can i edit it

        if i dont want to loose that variable scope & also i want to use strict then how can i edit it

        Its simple, use another variable that isn't $row

        my $what; for my $row ( $min .. $max ){ if( $data == $required ){ $what = $row; last; } } print "Data presented in:: $row \n";
Re: usage of "my" keyword
by wee (Scribe) on Aug 12, 2015 at 22:28 UTC
    You don't even need to declare $i at all:
    #!/usr/bin/perl use strict; use warnings; for (8 .. 27) { print "present value of the number is: $_\n"; }
Re: usage of "my" keyword
by sundialsvc4 (Abbot) on Aug 10, 2015 at 11:45 UTC

    Perhaps you are used to languages like PHP that do not require you to declare variables.   But there are two extremely compelling reasons to do this:

    (1) Tpyos:   Yeah, the day will come when, somewhere among thousands of lines of source-code, you will “fat-finger” something.   Without variable-declarations, the compiler cannot catch the error ... and, if the compiler does not catch the error, then, pragmatically speaking, neither can you.

    (2) Scope:   Undeclared variables basically exist “all over the program.”   They have whatever value they last contained, from whatever point in the program where their value may happen to have last been set.   Thus, “anywhere else in the program, and anytime,” can now interfere with the correct operation of ... “anywhere else in the program, and anytime.”

    The Perl language is designed to help address both of these issues, by obliging you to declare variables and by associating a “scope” (visibility + lifetime) to each variable depending on exactly where it is declared.   In this way, the Perl compiler can detect nefarious errors that, otherwise, you will never catch.   Those errors can (literally ...) cost you a fortune.   Never write software without the use strict; use warnings; pragmas in place.

Re: usage of "my" keyword
by taint (Chaplain) on May 10, 2016 at 17:17 UTC
    OK. While at this point, it will seem quite obvious. I'm going to list it, for completeness. As I would have thought it the first thing to show up. :)

    Here cant i declare a variabe without using my keyword.
    Error: Global symbol "$i" requires explicit package name at for.pl line 6.
    Technically, you can
    use strict; use warnings; my $number=8; no strict; # could have also used "no strict vars" $i=0; #if i remove my keyword it gives error (not now) for($i=0;$i<20;$i++) use strict; # back to strict { print "present value of the number is:"; print $number++; print "\n"; }
    OR, clobber them all up front:
    use strict; no strict vars; use warnings; $number=8; # look MA, no MY! $i=0; #if i remove my keyword it gives error -- not NOW! for($i=0;$i<20;$i++) # here either { print "present value of the number is:"; print $number++; print "\n"; }
    OK those were pretty much directly from the strictures documentation (which is why I felt they should have been included here). But why not illustrate another possibility -- global Variable Scoping in Perl: the basics?
    #!/usr/bin/perl -w our ( $number, $i ); use strict; $number=8; # NOTE the absence of my $i=0; # AGAIN no my used here for($i=0;$i<20;$i++) # OR here { print "present value of the number is:"; print $number++; print "\n"; }
    Cool, huh? Well, not really. While the PHP language practically encourages global variables. In most cases, it should be avoided. If for no other reason; security reasons. Ovid has written a nice overview, that outlines global variables scoping, titled: 'our' is not 'my', that better describes this.

    There. Now this feels complete :)

    --Chris

    ¡λɐp ʇɑəɹ⅁ ɐ əʌɐɥ puɐ ʻꜱdləɥ ꜱᴉɥʇ ədoH

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2024-04-25 17:41 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found