Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked
 
PerlMonks  

Re: How can I use 'split' with unknown amount of variables?

by rbc (Curate)
on Dec 30, 2001 at 08:43 UTC ( #135207=note: print w/replies, xml ) Need Help??


in reply to How can I use 'split' with unknown amount of variables?

try something like ...

my $s = "one|two|three|four"; (@items)=split /\|/, $s; print "NI = $#items+1\n@items\n";

... I hvae been drinking cheap wine so you
better double check :)
--
Its like a dog that can sing and dance.
It's remarkable because it can do it.
Not that it can do it well.

Replies are listed 'Best First'.
Re: Re: How can I use 'split' with unknown amount of variables?
by steves (Curate) on Dec 30, 2001 at 12:07 UTC

    I think bladex may be referring to the split behavior many people forget about: by default it strips null fields off the end. So if one line is: one|two|three|four but the next is five|six|| then the first split gets a 4 element array, the second gets a two element array. This can cause problems if the application always wants 4 fields regardless. The way around that is to use the seldom used 3rd arrgument to split, LIMIT. If you know how many fields you'll always have, set it to that number. Otherwise set it to a negative value to always keep null fields in each split line. See the docs for details or I can elaborate further.

      steves is right. I use split's LIMIT argument from time to time. It's quite handy.

      This illustration prints each element on separate line, showing the nulls:

      #!/usr/bin/perl -w use strict; my $item1 = "1,2,3,4,5"; my $item2 = "a,b,c,,"; my @split1 = split( /,/, $item1, 5); my @split2 = split( /,/, $item2, 5); # better yet, to set the size of the array at run-time... # my @split2 = split( /,/, $item2, ($#split1 + 1)); print "item1 has " . ( $#split1 + 1) ." elements:\n"; foreach(@split1){ print "'$_'\n"; } print "\nitem2 has " . ( $#split2 + 1) ." elements\n"; foreach(@split2){ print "'$_'\n"; }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://135207]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others pondering the Monastery: (2)
As of 2023-01-29 16:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?