Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

split(/:/, $t) splits also on white space

by Nagarjuna (Initiate)
on Sep 25, 2014 at 10:14 UTC ( [id://1101942]=perlquestion: print w/replies, xml ) Need Help??

Nagarjuna has asked for the wisdom of the Perl Monks concerning the following question:

The following perl code should print
A B:C D
A B
C D
but instead it prints
A B:C D
A
B
C
D

$t = "A B:C D";
@a =split(/:/, $t);
print $t. "\n";
foreach $b (<@a>) { print $b ."\n";}

I have used split before and never noticed such behavior.
I got the same problem on perl v5.6.1 running on Red Hat Linux release 7.3 (Valhalla) (2.4.33.2)
and
perl v5.14.2 running on Ubuntu 12.04.5 LTS (3.5.0-54-generic)

Am I missing something ? Thank you

Replies are listed 'Best First'.
Re: split(/:/, $t) splits also on white space
by Loops (Curate) on Sep 25, 2014 at 11:25 UTC

    As implied in the answer above, if you simply change (<@a>) to (@a) in your foreach loop, your code will work as you desire.

    With the angle brackets the elements of the @a array ("A B", "C D") are being interpreted as a perl glob. Each element is split on whitespace, and the combined result is 4 total elements, A, B, C, and D. That's what your foreach loop iterates over and prints out.

Re: split always splits also on white space (Perl v5.14.2) Ubuntu (12.04)
by Anonymous Monk on Sep 25, 2014 at 10:15 UTC
    Why are you using <@a>?
      <@a> is glob not readline ... neither of which you want to iterate over an array
      use strict; use warnings; use Data::Dump qw/ dd /; my $colons = "A B:C D"; my @notColons =split(/:/, $colons); dd( $colons, \@notColons ); __END__ ("A B:C D", ["A B", "C D"])

        Thank You AnonymousMonk
        for the prompt and exhaustive reply.
        I have also realized how much I have yet to meditate to become a perl monk !
        Thank you again

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2024-03-28 07:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found