Beefy Boxes and Bandwidth Generously Provided by pair Networks vroom
Pathologically Eclectic Rubbish Lister
 
PerlMonks  

Re^2: split and uninitialized variables

by ikegami (Patriarch)
on Sep 03, 2004 at 11:31 UTC ( [id://388310]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


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 12: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.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://388310]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.