in reply to splitting issues

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

Replies are listed 'Best First'.
Re: Re: splitting issues
by Anonymous Monk on Jan 24, 2002 at 21:05 UTC
    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.