http://www.perlmonks.org?node_id=388301


in reply to split and uninitialized variables

You can do
my ($x, $y, $z) = ('', '', ''); ($x, $y, $z) = split(',', $_);
OR
my ($x, $y, $z) = map { $_ || '' } split(',', $_);
to ensure the variables are initialised.

Update: Oops! I really need a new brain.

use strict; use warnings; $_ = "a,0,b"; my ($x, $y, $z) = split(',', $_); foreach ($x, $y, $z) { $_ = '' unless defined($_) } print "x = $x\ny = $y\nz = $z\n"; __END__ x = a y = 0 z = b

Replies are listed 'Best First'.
Re^2: split and uninitialized variables
by ikegami (Patriarch) on Sep 03, 2004 at 15:31 UTC

    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.

      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.
Re^2: split and uninitialized variables
by Fletch (Bishop) on Sep 03, 2004 at 15:33 UTC

    Your first one's not going to work.

    main::(-e:1): 0 DB<1> $_ = "a,b" DB<2> x ($x,$y,$z) = ('default') x 3 0 'default' 1 'default' 2 'default' DB<3> x ($x,$y,$z) = split( ',', $_ ) 0 'a' 1 'b' 2 undef
Re^2: split and uninitialized variables
by antirice (Priest) on Sep 03, 2004 at 15:33 UTC

    Both methods have problems:

    > perl -wl my ($x,$y,$z) = ('','',''); ($x,$y,$z) = split(',','a,b'); print "$x $y $z"; __END__ Use of uninitialized value in concatenation (.) or string at - line 3. a b > perl -wl my ($x, $y, $z) = map { $_ || '' } split(',', 'a,0,b'); print "$x $y $z"; __END__ a b

    The second one is easily fixed with:

    perl -wl my ($x, $y, $z) = map defined $_ ? $_ : '', (split(',', 'a,0,b'))[0..2 +]; print "$x $y $z"; __END__ a 0 b

    Update: Doh! Thanks !1 (silly lurker).

    antirice    
    The first rule of Perl club is - use Perl
    The
    ith rule of Perl club is - follow rule i - 1 for i > 1