"my $x;" in while or for block?

Discussion in 'Perl Misc' started by Am Nym, Nov 10, 2012.

  1. Am Nym

    Am Nym Guest

    Bad practice to declare a variable w/in a while or for block?

    Is this OK?:

    $ cat bar
    #!/usr/bin/perl
    use strict;
    use warnings;

    my %foo = (
    bob => "green",
    sue => "blue",
    );

    for (keys %foo)
    {
    my $x;
    # acceptable?? (want $x to be undefined at start of each iteration)

    printf "hi\n" unless(defined ($x));
    $x = 1;
    printf "HO\n" unless(defined ($x));

    print "$_\n\n";
    }
    $ ./bar
    hi
    sue

    hi
    bob

    --
    thanks
    Am Nym, Nov 10, 2012
    #1
    1. Advertising

  2. Am Nym

    Am Nym Guest

    Ben Morrow <> writes:

    > Quoth Am Nym <>:
    >> Bad practice to declare a variable w/in a while or for block?

    >
    > No, absolutely not. You should declare your variables in the smallest
    > scope you can.


    Thanks, appreciate the help.

    >> Is this OK?:
    >>
    >> $ cat bar
    >> #!/usr/bin/perl
    >> use strict;
    >> use warnings;
    >>
    >> my %foo = (
    >> bob => "green",
    >> sue => "blue",
    >> );
    >>
    >> for (keys %foo)
    >> {
    >> my $x;
    >> # acceptable?? (want $x to be undefined at start of each iteration)

    >
    > Yes, this is good practice.


    alright ;->
    Am Nym, Nov 11, 2012
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Showjumper
    Replies:
    1
    Views:
    693
    Showjumper
    Mar 19, 2005
  2. Noozer

    Block DIV within a block DIV?

    Noozer, Jan 6, 2005, in forum: HTML
    Replies:
    3
    Views:
    11,349
    Mitja
    Jan 6, 2005
  3. Andy
    Replies:
    0
    Views:
    525
  4. morrell
    Replies:
    1
    Views:
    936
    roy axenov
    Oct 10, 2006
  5. Alvin
    Replies:
    8
    Views:
    959
Loading...

Share This Page