in reply to Perl array declaring

When strict refs, we should declare a variable like my @string to use it in the program. A variable can be declared only once in a single program.

Replies are listed 'Best First'.
Re^2: Perl array declaring
by tobyink (Canon) on Jun 01, 2013 at 19:48 UTC

    Variables can be declared as many times as you like...

    use strict; our $foo = 123; our $foo; our $foo; our $foo; our $foo; print(our $foo, "\n");

    Also, strict refs don't force you to declare a variable...

    use strict "refs"; $foo = 123; # ok print "$foo\n"; # still ok

    ... it is strict vars that forces you to declare variables.

    package Cow { use Moo; has name => (is => 'lazy', default => sub { 'Mooington' }) } say Cow->new->name
      Variables can be declared as many times as you like...
      True only for global variables, and even then, not without warnings. Change your 'our' to 'my' and your program no longer works. You are creating new variables with the same name. Warnings inform you that the new variable masks an earlier declaration.
      Bill

        Variables can be declared as many times as you like...

        True only for global variables, and even then, not without warnings. Change your 'our' to 'my' and your program no longer works. You are creating new variables with the same name. Warnings inform you that the new variable masks an earlier declaration.

        I surely understand what you meant to say and agree with what you intended to say, Bill, but lexical variables can indeed be declared as many times as you like, provided they are not declarred in the same lexical scope. For example, the following code declares the same lexical variable four times without any error or warning:

        use strict; use warnings; my $var = 1; { my $var = 2; print $var, "\n", } print "$var \n"; foreach my $var (1..5) { print $var, "\n"; } print double(7); sub double {my $var = shift; return 2 * $var;}

        and happily prints:

        $ perl scope.pl 2 1 1 2 3 4 5 14

        Which does not mean at all that I recommend doing that. It can be done, and is useful sometimes, but we should avoid leading to obfuscation.