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

I am using local vaiables in a sub. But with @wire2 it is not working. The history of this variable is keept like I would expect it for a global variable.
#!/usr/bin/perl wr_module("1"); wr_module("2"); wr_module("3"); exit; sub wr_module { my $x=shift; my $wire0; my @wire1; my @wire2; print("Adding $x "); $wire0.=$x; $wire1[1].=$x; $wire2{"a"}.=$x; print(" => $wire0 :: $wire1[1] :: $wire2{\"a\"} \n"); }
The script returns:
Adding 1 => 1 :: 1 :: 1 Adding 2 => 2 :: 2 :: 12 Adding 3 => 3 :: 3 :: 123
I would expect:
Adding 1 => 1 :: 1 :: 1 Adding 2 => 2 :: 2 :: 2 Adding 3 => 3 :: 3 :: 3
Do you have an idea, why the "my" is not working for @wire2 ? Thanks for your help !

Replies are listed 'Best First'.
Re: using local variables
by Corion (Patriarch) on Mar 16, 2016 at 10:24 UTC

    Perl can help you a lot with your code if you let it. In your case, adding the line use strict; near the top of your program will make Perl tell you about undeclared variables.

    In your case, you're declaring a variable @wire2 as an array, but you are actually using a hash %wire2 in the line:

    $wire2{ "a"} .= $x;

    This is why it's always recommended that you add the two lines near the top of your scripts:

    use strict; use warnings;
      Thanks. That helped me a lot.
Re: using local variables
by Eily (Monsignor) on Mar 16, 2016 at 10:30 UTC

    For your information, when a single word is used as the key in a hash, perl allows you to omit the quotes. So $wire2{"a"} and $wire2{a} are equivalent, and "$wire2{a}" does what you want.

    And ++ to Corion for strictures and warnings.