in reply to Re: split and uninitialized variables
in thread split and uninitialized variables

Your first solution

my ($x, $y, $z) = ('', '', ''); ($x, $y, $z) = split(',', $_);

won't work. Any values assigned in the first line will get overwritten in the second line:

$_ = 'a,b'; my ($x, $y, $z) = ('', '', ''); ($x, $y, $z) = split(',', $_); print(defined($z)?'defined':'undefined', "\n"); # prints undefined.

Your second solution

my ($x, $y, $z) = map { $_ || '' } split(',', $_);

erases any '0'. Try:

my ($x, $y, $z) = map { defined($_)?$_:'' } (split(',', $_))[0..2];

Personally, I'd go with the simple my ($x, $y, $z) = (split(',', $_), ('') x 3); solution mentioned elsewhere.

Update: Added missing [0..2] as pointed out by Roy Johnson. Thanks.

Replies are listed 'Best First'.
Re^3: split and uninitialized variables
by Roy Johnson (Monsignor) on Sep 03, 2004 at 16:09 UTC
    Actually, the map solution doesn't work, because split doesn't return three elements, so you'd need to make it
    my ($x, $y, $z) = map { defined($_) ? $_ : '' } (split(/,/, $_))[0..2] +;

    Caution: Contents may have been coded under pressure.