John W. Krahn wrote:
Rob Dixon wrote:
John W. Krahn wrote:
Gauthier, Dave wrote:
Getting unwanted list elements when using split with regex. Here's an
example....
$str = "abc=In";
@arr = split(/[a-zA-Z0-9]/,$str);
foreach $a (@arr)
{print "$a\n";}
I get...
<> <> <> <=>
^ ^ ^ ^
O T T F
n w h o
e o r u
e r
e
If I change "abc=In" to "abcdef=In", I get 6 unwanetd null elements (one
per char before the "="). I was expectiing a single element list
with arr[0] = "=".
What's Up ? Is ther a clen way to prevent creating these unwanted
elements?
In your example the string "abc=In" is being split using the expression
/[a-zA-Z0-9]/. That expression matches in the string at positions 0,
1, 2, 4
and 5 therefore split will produce a list of *six* elements:
$ perl -le'
$str = "abc=In";
print ++$x, ": <$_>" for split /[a-zA-Z0-9]/, $str, -1;
'
1: <>
2: <>
3: <>
4: <=>
5: <>
6: <>
Your example only shows four because split automatically discards any
trailing
empty elements.
[snip]
Er, but he shows /six/ elements; and split /doesn't/ discard trailing empty
elements. Or am I misunderstanding you John?
perldoc -f split
split /PATTERN/,EXPR,LIMIT
split /PATTERN/,EXPR
split /PATTERN/
split Splits the string EXPR into a list of strings and returns that
list. By default, empty leading fields are preserved, and empty
trailing ones are deleted. (If all fields are empty, they are
considered to be trailing.)
Thanks John. I was reading the wrong part of the post, and you showed me a
corner of Perl that I didn't know about.
Rob
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/