Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

splitting a string

by Anonymous Monk
on Dec 04, 2008 at 06:48 UTC ( [id://727880]=perlquestion: print w/replies, xml ) Need Help??

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


Hi Monks,

I am not able to split a string correctly.

The string is as follows:
my $string = "/home/source::::::::DATE:SUBJECT:NAME::::::";
If i use a the following code i am but able to split it correctly.
my @array = split(":",$string);
There are only 11 elements in the array.

But there are 16 semicolons in that string.

So there should be 16 elements in that array.

When i print the array i am not getting the empty spaces after the value "NAME" in the string.

Can any one help me on this???

Replies are listed 'Best First'.
Re: splitting a string
by graff (Chancellor) on Dec 04, 2008 at 07:17 UTC
    As described in the docs for split, there's an optional 3rd arg, which says how many elements you want returned; "-1" returns all possible, even those that happen to be empty strings after the last non-empty element. (Default is to truncate the return list after the last non-empty element.)
Re: splitting a string
by prasadbabu (Prior) on Dec 04, 2008 at 07:27 UTC

    Hi,

    From split doc,

    "Empty trailing fields, on the other hand, are produced when there is a match at the end of the string (and when LIMIT is given and is not 0), regardless of the length of the match"
    .

    use strict; use warnings; my $string = "/home/source::::::::DATE:SUBJECT:NAME::::::"; my @array = split(/:/,$string, -1); $" = '><'; print "<@array>\n"; print scalar(@array); output: ------- </home/source><><><><><><><><DATE><SUBJECT><NAME><><><><><><> 17

    Prasad

Re: splitting a string
by lakshmananindia (Chaplain) on Dec 04, 2008 at 09:47 UTC
    From the perldoc documentation, if the LIMIT (3rd Argument) is unspecified or zero, trailing null fields are stripped off. If you don't want that then pass the LIMIT as -1.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2024-04-25 21:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found