in reply to does perl have a concept of "int main()"? (variable scoping question)

Lexical variables declared (with my) outside of of any block or function will be visible until the end of the file. Lexical variables declared in a block or in a function will be accessible only until the end of the block or the function. You can create a pseudo main() function if you wish to reduce the scope of your variables.
  • Comment on Re: does perl have a concept of "int main()"? (variable scoping question)
  • Download Code

Replies are listed 'Best First'.
Re^2: does perl have a concept of "int main()"? (variable scoping question)
by LanX (Saint) on Dec 05, 2013 at 21:56 UTC
    > You can create a pseudo main() function if you wish to reduce the scope of your variables

    one (or multiple) simple blocks are sufficient

    { my $var; #... maincode ... } sub function1 { # can't access $var }

    Cheers Rolf

    ( addicted to the Perl Programming Language)

      Sure, blocks would be sufficient, I totally agree. But if you really want to mimic the C/C++ behavior (I am not really convinced by the idea, but let's assume you want to do it for the sake of argument), then you could have something like this:
      use strict; use warnings; main(); sub main { my $var1 = "foo"; my $var2 = "bar"; my $return_val = process_data ($var1, $var2); # ... }
      then all your variables are truly "local" (I really mean lexically scoped). But I think that Perl offers better alternatives; trying to write C code in Perl is probably not a very good idea. I was only saying that it can be done if you really want to.

        But if you really want to mimic the C/C++ behavior (I am not really convinced by the idea, but let's assume you want to do it for the sake of argument), .... trying to write C code in Perl is probably not a very good idea

        Perl lets you get away with a lot , but most noobs won't understand it, so if you're going to emulate something until you learn what's what, its good to emulate

        Main( @ARGV ); exit( 0 );

        After you learn what's what, you'll know why you're emulating good practices and continue doing it :) even if it resembles or mimics C

        Just because perl allows and we can read and follow spaghetti code of the type  my $...; sub foo {} my $...; foo(); ... sub bar {} ... bar(); doesn't make it a good idea ; its down right irritating for no other reason than to be irritating; so you used cat as your editor, congratulations, now use pico to fix it :)

        chromatics free book Modern Perl a loose description of how experienced and effective Perl 5 programmers work....You can learn this too. discusses this in Chapter 10 under "Handling Main"

        Its also discussed in tyes template at (tye)Re: Stupid question (and see one discussion of that template at Re^2: RFC: Creating unicursal stars