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

Hi,
I was just wondering if this is possible to implement easily:
a user provides a list of symbols, say, ;:-, any of which are then used to split a line?
In other words, if I have an array of symbols, can I then somehow convert it to a pattern? Thanks!

Replies are listed 'Best First'.
Re: splitting a line by user-defined separators
by davorg (Chancellor) on Jul 14, 2006 at 14:28 UTC

    Build your own regex out of your user's input.

    my @match = qw(; : -); my $match = join('|', map { "\Q$_" } @match); if ('random-text' =~ /$match/) { print "yep\n"; } else { print "nope\n"; }

    Note the use of \Q in case your users input regex metacharacters. \Q escapes them so they aren't treated as metacharacters.

    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: splitting a line by user-defined separators
by holli (Abbot) on Jul 14, 2006 at 15:37 UTC
    $sep = quotemeta(";:-"); while (<>) { @line = split /[$sep]/; }


    holli, /regexed monk/
Re: splitting a line by user-defined separators
by shmem (Chancellor) on Jul 14, 2006 at 14:16 UTC
    uhm, let's see...
    perl -le '$_="foo;bar:quux-blorflydick";my $p = "[".shift()."]"; print + "@{[split/$p/,$_]}"' ';:y-' foo bar quux blorfl dick

    Yes. It's possible. Just make your split chars into a character class and use that in split (escaping meta-chars where necessary).

    --shmem

    _($_=" "x(1<<5)."?\n".q·/)Oo.  G°\        /
                                  /\_¯/(q    /
    ----------------------------  \__(m.====·.(_("always off the crowd"))."·
    ");sub _{s./.($e="'Itrs `mnsgdq Gdbj O`qkdq")=~y/"-y/#-z/;$e.e && print}
Re: splitting a line by user-defined separators
by a11 (Novice) on Jul 14, 2006 at 15:13 UTC
    Thanks a lot! I didn't know that it is possible to make a regex from a string simply by writing /$string/ !