in reply to Split returning one element
Here's my take on this approach. Note that the LIMIT parameter of split is used to avoid generating a list of useless substrings. And, of course, the guts of the function can still be extracted and used inline.
Update: Of course, it's always possible to go a little nuts with this kind of thing. Here's a version that returns an arbitrary list of split substrings (but still without much in the way of data validation):>perl -wMstrict -le "sub my_split { my ($elem, $rx, $string) = @_; return (split $rx, $string, $elem+2)[$elem]; } my $s = 'a:b:c:d:e'; print q{'}, my_split($_, ':', $s), q{'} for 0, 1, 3, 4, 5, 9999; " 'a' 'b' 'd' 'e' '' ''
>perl -wMstrict -le "sub my_split { my $rx = shift; my $string = shift; return unless @_; my $max_i = (sort { $a <=> $b } @_)[-1]; return (split $rx, $string, $max_i+2)[@_]; } my $s = 'a:b:c:d:e'; print my_split(':', $s, 0); print my_split(':', $s, 3, 2); print my_split(':', $s, 5, 4, 9999); print my_split(':', $s); " a dc Use of uninitialized value in print at -e line 1. Use of uninitialized value in print at -e line 1. e
|
|---|