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

Hello Monks,

Is there a nice way to initialise some variables to the same value ?

 my ($a,$b,$c)=(1,1,1);

Here I have to count and have the same number of entries in both arrays.

Nice would be something like: " my ($a,$b,$c)=1 for all;"

Many thanks

Replies are listed 'Best First'.
Re: Initialisation of variables
by haukex (Archbishop) on Apr 08, 2023 at 07:11 UTC

    I would consider a ton of lexical variables code smell, especially if there's too many for you to count, and you are probably better off with a data structure like a hash or array. (see also perldsc)

    But to avoid the repetition in the example you showed you can write: my ($x,$y,$z) = (42) x 3; (repetition operator)

Re: Initialisation of variables
by 1nickt (Canon) on Apr 08, 2023 at 10:29 UTC

    Hi,

    When there are only two (or three) I sometimes write:

    my $foo = my $bar = my $baz = 1;

    (But don't use the variable names $a and $b -- they are special in Perl. $x, $y, $z is a good alternative, or even better, use descriptive names.)

    Hope this helps !


    The way forward always starts with a minimal test.
Re: Initialisation of variables
by tybalt89 (Monsignor) on Apr 08, 2023 at 07:52 UTC

      !! Perfekt Solution !!

      May thanks