Declare multiple variables on one line in perl

I'm new to Perl, but I'll tell you what I've learned so far.

I'm going to change to using $start and $end instead of $a and $b, because $a and $b are special variables that are always declared.

To answer your original question, you can declare and assign multiple variables in a single line like this:

my ($start, $end) = (1, 2);

Personally, I find that about the same typing and less clear than having each on a separate line:

my $start = 1;
my $end = 2;

However, I think it is useful for assigning subroutine parameters to named variables, because subroutine parameters come in a list called @_:

use strict;

sub print_range {
    my ($start, $end) = @_;
    print "Range is from $start to $end.\n";
}

print_range(10, 20); # => Range is from 10 to 20.

You can see some more quirks of the my statement in the documentation, including a way to ignore some of the values in the list.


Below is the method to declare multiple variable in one line in perl:

my ($day, $mon, $year, $hr, $min, $sec) = (0) x 6;

Here, all the above variables has been initialized with 0. The repetition operator 'x' is used.


No. Variables declared by my are only named once the next statement begins. The only way you can assign to the newly created variable is if you assign to the variable it returns. Think of my as new that also declares.

As for your particular code,

my $a=1, $b=2;

means

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

Obviously, no good.

If you had used variables that weren't already declared[1], you would have gotten a strict error.


  1. $a and $b are predeclared in every namespace to facilitate the use of sort.

Tags:

Perl