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

how do i split on the first ':' and only the first ':' of a string that may or maynot contain more than one ':' ? thank you.

Replies are listed 'Best First'.
Re: splitting issues
by Chmrr (Vicar) on Jan 24, 2002 at 10:59 UTC

    Look into the third argument, the "limit", on the split help page. Type "perldoc -f split" to get this on your local machine. I will also pimp How to RTFM about how to find the answers to easy questions.

    perl -pe '"I lo*`+$^X$\"$]!$/"=~m%(.*)%s;$_=$1;y^`+*^e v^#$&V"+@( NO CARRIER'

Re: splitting issues
by grep (Monsignor) on Jan 24, 2002 at 10:56 UTC
    You can do a regex:

    /^([^:]+):(.+)/; my $first = $1; my $second = $2;


    UPDATE:Chmrr has better solution - as always TIMTOWTDI

    grep
    grep> cd pub
    grep> more beer
      Using split() with a limit is indeed better. But I still feel like elaborating some on your regex, for the heck of it. ;)

      In my opinion, your regex is too restrictive. It requires a colon and something after it. This isn't the way split() works. To make it more analogous, I'd make
      /([^:]*):?(.*)/s; # Keeping it simple /([^:]*)(?::(.*))?/; # Making it even more analogous.
      (Note also the s modifier that's very easy to forget.)

      Of course, it's not perfect. There are issues about the length of the returned list; if the "extra" trailing element (that split() would not even return) should be undef or ''; etc.

      The second regex returns '' as second element if there was a colon, undef if there was no colon. This is as close as one gets I believe.

      Just for fun:
      grep defined, /([^:]*)(?::(.*))?/;
      I can't find any differences between this and split(/:/, $_, 2), except for scalar context execution, were you get rid of the old @_ behaviour.
        Ack, the s modifier it was... Forgot it in the last two regexes myself. :)

        All regexes should of course have the s modifier.
Re: splitting issues
by belg4mit (Prior) on Jan 24, 2002 at 21:41 UTC
    You can also use index with substr, in the form of:
    substr($str, 0, 0, index($str, ':'));

    UPDATE: And of course the complement to get the remainder...

    --
    perl -pe "s/\b;([st])/'\1/mg"