Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

question on perl's split function

by greatshots (Pilgrim)
on Oct 22, 2007 at 09:03 UTC ( [id://646387]=perlquestion: print w/replies, xml ) Need Help??

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

monks,

#!/usr/bin/perl my $string = "///a/b////c"; my @arr = split("\/*",$string); print ":" , join("_",@arr) , ":\n"; Output :- :_a_b_c:
but I want the out put as ":a_b_c:", I changed the join as
print ":" , join("_",@arr[1..$#arr]) , ":\n";
But in the above join explicitly I am removing the 0 index from the array to avoid. Is there a standard way to chop this null string in split function itself.

Replies are listed 'Best First'.
Re: question on perl's split function
by GrandFather (Saint) on Oct 22, 2007 at 09:31 UTC

    The leading string of /'s generates an empty first element. One fix is:

    my @arr = grep {length} split("/+",$string);

    Perl is environmentally friendly - it saves trees
Re: question on perl's split function
by moritz (Cardinal) on Oct 22, 2007 at 09:23 UTC
    Unrelated to the rest of your question: chances are that the split doesn't do what you want it to, because it splits at the empty string.

    Try this instead: my @arr = split m{/+}, $string;

Re: question on perl's split function
by rminner (Chaplain) on Oct 22, 2007 at 09:27 UTC
    if you only want the none empty strings, then you can achieve it like this:
    my $string = "///a/b////c"; my @arr = grep {$_ ne ''} split("\/+",$string); print ":" , join("_",@arr) , ":\n";
    Also: moritz is right, that /* matches 0 or more slashes, so it would also split the string where you wouldn't expect it to split the string. Simply try using the following string with your split regex of /*:
    my $string = "//foo//bar///";
    then you'll understand the problem. + is what you need as it matches 1..n ocurrences of the previous char.
Re: question on perl's split function
by Prof Vince (Friar) on Oct 22, 2007 at 10:00 UTC
    You can also use a regexp :

    my @arr = $string =~ m,([^/]+),g;

    Please note that Perl's split isn't PHP's and expects a pattern (or ' ') as its first argument, so you'd better not split on a string if you don't know what's happening there.

Log In?
Username:
Password:

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

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

    No recent polls found