in reply to assigning to array from a split with some empty fields

Using split without the third argument LIMIT will strip trailing null fields. instead of  @array = split(/\|/,$text) try  @array = split(/\|/,$text,-1). The -1 for LIMIT acts as if an arbitrarily large limit has been specified. The one catch is that the position after the last seperator will be included in the array. In your example, scalar @array = 16 not 15. You could work around this by taking (scalar @array) - 1 or maybe just $#array. Of course, I'm assuming that the seperator is a terminating character on the string and that something like  $text = 'a|b|c|||||||||e||||q'; will not occur. If it might, then scalar @array = 16 is the correct count vice 15

Replies are listed 'Best First'.
Re: Re: assigning to array from a split with some empty fields
by flyingmoose (Priest) on Apr 14, 2004 at 18:30 UTC
    What I am about to do is stupid (and the long way around), but I just feel like playing around today... so here's a different and more generic way to think about it ... fixing bad input... this should work in scenarios other than just split, call it "thinking outside the box", if you will. Of course, I prefer "there is no box". But there might be a spoon. Or at least a spork. Anyway....
    $text = 'a|b|c|||||||||e||||'; @array = split(/\|/,$text); print join '-', @array;

    can become ...

    $text = 'a|b|c|||||||||e||||'; # our input might have holes in it! $text =~ s#\|\|#\|NULL\|#g; # make holes read as 'NULL' @array = map { $_ eq 'NULL' ? undef : $_ } split(/\|/,$text); print join '-', @array;

    Code is of course untested, but you see the general madness of it. We're filling up a hole with something, digging up the hole, and then getting the hole back just like we left it :) Ok I just like overusing map. If you have a map, everything looks like a nail. Good thing Magellan didn't have a map.