Or you could use a regex. That has the benefit of not removing content from $source.while (length $source) { # make only one split (creating 2 parts) (my($rec),$source) = split /;/, $source, 2; # ... }
Or, if you're a major fan of C, I offer you strtok() in Perl:while (my ($rec) = $source =~ /\G([^;]*)(?:;|$)/g) { # ... }
There are two special flags to send to this function -- RE_MAGIC is sent in place of the pattern, and signifies Perl's special split(' ', ...) behavior; C_STYLE splits on multiple occurrences of tokens (so that "a--b" split on "-" will return a and b, and no empty string).use constant RE_MAGIC => bless [], 'RE_MAGIC'; use constant C_STYLE => bless [], 'C_STYLE'; { my ($re,$str); sub strtok { my ($s,$pat,$opt) = @_; if (defined $s) { local $^W; # in case $pat/$opt isn't a ref $re = ref($pat) eq "RE_MAGIC" ? qr/(?!\s*$)\s*(\S*)/ : $opt && ref($opt) eq "C_STYLE" ? qr/(?!(?:$pat)*$)((?:(?!$pat).)*)(?:(?:$pat)+|$)/ : qr/(?!(?:$pat)*$)((?:(?!$pat).)*)(?:(?:$pat)|$)/; $str = $s; } else { croak "no pattern for strtok()" if not defined $re; } $str =~ /\G$re/g and return $1; undef $re; undef $str; } } my $rec = strtok($source, ';'); while (defined $rec) { # ... $rec = strtok(); }
In reply to Re: Split long string MANY times?
by japhy
in thread Split long string MANY times?
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |