IMHO, the custom function approach is not such a bad way to go. For instance, it allows for data validation, e.g., checking for a negative element index.

Here's my take on this approach. Note that the  LIMIT parameter of split is used to avoid generating a list of useless substrings. And, of course, the guts of the function can still be extracted and used inline.

>perl -wMstrict -le "sub my_split { my ($elem, $rx, $string) = @_; return (split $rx, $string, $elem+2)[$elem]; } my $s = 'a:b:c:d:e'; print q{'}, my_split($_, ':', $s), q{'} for 0, 1, 3, 4, 5, 9999; " 'a' 'b' 'd' 'e' '' ''
Update: Of course, it's always possible to go a little nuts with this kind of thing. Here's a version that returns an arbitrary list of split substrings (but still without much in the way of data validation):
>perl -wMstrict -le "sub my_split { my $rx = shift; my $string = shift; return unless @_; my $max_i = (sort { $a <=> $b } @_)[-1]; return (split $rx, $string, $max_i+2)[@_]; } my $s = 'a:b:c:d:e'; print my_split(':', $s, 0); print my_split(':', $s, 3, 2); print my_split(':', $s, 5, 4, 9999); print my_split(':', $s); " a dc Use of uninitialized value in print at -e line 1. Use of uninitialized value in print at -e line 1. e

In reply to Re: Split returning one element by AnomalousMonk
in thread Split returning one element by MonkDrew

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.