#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    4
    Rep Power
    0

    Scope of variables declared in main


    I'm seeing a variable used in a subroutine that's not being declared anywhere. It's declared somewhere in main so can subroutines see those as well?
  2. #2
  3. !~ /m$/
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    May 2004
    Location
    Reno, NV
    Posts
    4,259
    Rep Power
    1810
    Yes, they can.

    Code:
    #!/usr/bin/perl
    use strict;
    use warnings;
    
    my $text = "testing, testing\n";
    print_test_string();
    
    sub print_test_string {
       print $text;
    }
    Not a good practice.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Aug 2013
    Posts
    4
    Rep Power
    0
    Originally Posted by keath
    Yes, they can.

    Code:
    #!/usr/bin/perl
    use strict;
    use warnings;
    
    my $text = "testing, testing\n";
    print_test_string();
    
    sub print_test_string {
       print $text;
    }
    Not a good practice.
    thanks yea it feels so weird
  6. #4
  7. wizard
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jul 2009
    Location
    The Great White North
    Posts
    79
    Rep Power
    138
    Originally Posted by enoh
    I'm seeing a variable used in a subroutine that's not being declared anywhere. It's declared somewhere in main so can subroutines see those as well?
    Technically, there's no main in Perl. Could you post example code?
    __END__

    I love Perl; it's the only language where you can bless your thingy.
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2012
    Posts
    832
    Rep Power
    496
    Lexical variables that are declared outside any function or block generally have a scope from the place where they are defined until the end of the file. This makes them sort of "global" variables, but it is rarely a very good idea to use them as such.

IMN logo majestic logo threadwatch logo seochat tools logo