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

How can I split on only the first occurence of a character?

i.e. I want a variation on the following code to populate $val with 'MYVAL=2'

($key, $val) = split (/=/, 'MYKEY=MYVAL=2');

Thanks, monks!

Replies are listed 'Best First'.
Re: split command
by ikegami (Patriarch) on Feb 21, 2007 at 18:48 UTC
    my ($key, $val) = split(/=/, 'MYKEY=MYVAL=2', 2);
      Thank you!

        or

        my ($key, $val) = 'MYKEY=MYVAL=2' =~ /^([^=]*)=(.*)/s;
Re: split command
by monster_death (Beadle) on Feb 21, 2007 at 23:57 UTC
    split /PATTERN/,EXPR,LIMIT

  • split /PATTERN/,EXPR
  • split /PATTERN/
  • split

    Splits the string EXPR into a list of strings and returns that list. By default, empty leading fields are preserved, and empty trailing ones are deleted. (If all fields are empty, they are considered to be trailing.)

    In scalar context, returns the number of fields found and splits into the <code class="inline">@_</code> array. Use of split in scalar context is deprecated, however, because it clobbers your subroutine arguments.

    If EXPR is omitted, splits the <code class="inline">$_</code> string. If PATTERN is also omitted, splits on whitespace (after skipping any leading whitespace). Anything matching PATTERN is taken to be a delimiter separating the fields. (Note that the delimiter may be longer than one character.)

    If LIMIT is specified and positive, it represents the maximum number of fields the EXPR will be split into, though the actual number of fields returned depends on the number of times PATTERN matches within EXPR. If LIMIT is unspecified or zero, trailing null fields are stripped (which potential users of <code class="inline">pop</code> would do well to remember). If LIMIT is negative, it is treated as if an arbitrarily large LIMIT had been specified. Note that splitting an EXPR that evaluates to the empty string always returns the empty list, regardless of the LIMIT specified.

    A pattern matching the null string (not to be confused with a null pattern <code class="inline">//</code> , which is just one member of the set of patterns matching a null string) will split the value of EXPR into separate characters at each point it matches that way