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

Okay, people, she's BAAAACK! My apologies for the elementary nature of my questions, but I am not now, nor have I ever been, a programmer. Closest I've come is JCL maintenance on MVS mainframes, which kind of explains why I have this question....

What is the syntax for assigning values to local variables? Here are a couple of examples:

local $GTENV = ltcd; # local = available for whole script? my $BNAME = ICVALID; # my = NOT available to subroutines? my $GTSTARTUP_T = "O:\Tools\GraphTalkDeveloper\R3212\bin\GTvrtt.exe"; + # enclose values w/ spec chars in ""s?

Is there a standard for how many spaces to leave between the variable name and the assignment operator? How does one know whether to enclose a value in single-quotes, double-quotes, parentheses, or nothing? Does it look like I understand correctly (if at a really basic level) the use of "my" vs. "local"?

I SWEAR I have RTFM, so to speak (searched online & in the 4 Perl books I have), but I must have missed it, assuming it's there. Any hints on where to find the answers? Thanks for your patience; you monks seem to be to have the largest volume of it of any usenets.

20060427 Janitored by Corion: Added formatting, code tags

Replies are listed 'Best First'.
Re: local variable syntax
by fishbot_v2 (Chaplain) on Apr 26, 2006 at 23:37 UTC
    Does it look like I understand correctly (if at a really basic level) the use of "my" vs. "local"?

    No, not really. I strongly recommend MJD's Coping with Scoping. In summary, you basically never want to use local.

    You should also read perlsyn again, if you haven't. White space before and after = is optional, but good style. You should always quote non-numeric literals, normally with double-quotes. Variables interpolate in double-quotes, but not in single-quotes. Parentheses are for lists, which you can store in arrays.

    I am glossing over a lot of details. It sounds like you need to read those 4 books again, or get better ones. These are fairly basic things.

    And you also should read this: Writeup Formatting Tips

      Thanks, fishbot. You know, after I posted this inquiry, I found "Coping with Scoping", and REALLY felt like a fool for asking. I'll also go back to perlsyn; obviously I missed something in there. Thanks again for your patience; the last time I did any programming was in school, and that was 25 years ago, and it was COBOL and BASIC, two of the easiest languages to learn.

        Welcome to Perl, and best of luck.

        Sometimes, if you are starting, diving right into the specs can be pretty overwhelming. And the bundled perldocs are geared primarily towards programmers. Working through a good beginner book is a good place to start, sounds like you are working on that. There are also Tutorials here at PM, too. This one does a better job of answering your question about quotes.

      In summary, you basically never want to use local.

      local is widely misunderstood. The best evidence of this is the frequency of statements like "never use local."

      It's more accurate and useful to say that local operates on all variables... except lexical (my) variables. It isn't just for localizing values of whatever package globals your program may have, it is essential for the special globals like $_ and @ARGV.
      Furthermore — and this useful fact is often missed — it can localize values in variable spaces which are automatically allocated by the interpreter — for example, elements of arrays and hashes.

      use Data::Dumper; use strict; use warnings; my %h = ( foo => 1 ); { local $h{'foo'} = 2; print Dumper \%h; } print Dumper \%h;
      $VAR1 = { 'foo' => 2 }; $VAR1 = { 'foo' => 1 };

      I would summarize by saying that As different as lexical variables are from package variables, so is local from my.
      local is a run-time function, whereas my is a compile-time keyword (with some run-time effects).
      local is very useful in its own way. It is by no means a drop-in replacement for my

      We're building the house of the future together.

        Well, I said "basically" never. Like all blanket statements, there are exceptions. Perhaps I should have said: Use my by default, use local when you understand why you can't use my in a specific situation. You can create 'stack-like' aggregates with local as you demonstrate, but you need a very good reason.

        # some good reasons: # if you modify a side-effect global like $/, # do it in the smallest scope possible: my $slurped = do { local $/; <$some_Fhand> }; # override an element of a global aggregate in a # limited scope: { local $SIG{"ALRM"} = \&some_handler; alarm $timeout; some_action(); }

        Of course, I agree that understanding the difference is much better than applying a blanket maxim. (Which is why I pointed to an article that does just that.)

Re: local variable syntax
by davido (Cardinal) on Apr 27, 2006 at 03:31 UTC

    Welcome BAAAACK! We are happy to have you participate here. But if you plan to post in the future, have a look at Writeup Formatting Tips. Your post, the way it's currently (un)formatted makes it next to impossible for people to recognize the code you've taken the time to show us. The Janitors can (and probably will) clean it up for you. But you're better off cleanly formatting your posts in the first place, so they'll be just how you want them, and so people can actually answer them.

    As for your question, I know that others have pointed out a few articles to examine. I just wanted to add a comment or two.

    First, learn to use strict;. This will force you to use lexical variables (my variables) instead of globals. Starting down that road is taking the first step down the road of success. Next, understand that local simply pushes a package global's current value out of sight onto a sort of internal stack, allowing you to give it a new value such that when the "local" version eventually passes out of scope, the original value is restored. ...it's a little more complex than that, but that's the general idea. This really isn't what you want, most of the time. The best use for local is to ensure that changes you make to Perl's special variables don't propigate beyond the narrowest scope possible. There are, of course, other uses, but none of them are considered beginning topics.

    On the other hand, my variables (lexical variables) are truely local to the lexical scope in which they're declared and defined. That's the compartmentalization that you need when developing scripts beyond a dozen or so lines long. Take the time to become familiar with how they work, and you'll be well on your way to a successful learning experience.


    Dave

Re: local variable syntax
by cdarke (Prior) on Apr 27, 2006 at 01:32 UTC
    A full answer would take a book, but I'll do my best.
    'What is the syntax for assigning values to local variables?' If you don't know the difference between 'local' and 'my', then use 'my'. 'local' variables are specialised and not often needed.
    'my' variables can be visibile to other subroutines in the same script file - it is a question of where you declare them.
    It is generally considered to be 'bad form' to globally share variables like this.
    'Is there a standard for how many spaces to leave between the variable name and the assignment operator?' Answer: no, just be consistent.
    How does one know whether to enclose a value in single-quotes, double-quotes, parentheses, or nothing?' Single-quotes surround unalterable text - we don't want perl to mess with the text within single quotes. Using double quotes invites perl to 'interpolate' special characters. Usually use double quotes around scalars ($var) and arrays (@fred) and characters like \n, \t.
    Parentheses are used for several things in Perl, but around variables it indicates a list. Nothing around a variable is usually fine, but around text is a bareword, which is usually wrong.
    If you have written a program then you are a programmer - there is no going back. Ask, crib other people's code, practice. Never stop learning.