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

Hey monks,

Quick, maybe dumb question: I've got some text files with lines made up of values separated by a single char. I need to read the lines and split them. The separator char may change between files, so it's defined as a variable in the script.

The problem comes when the separator char is a Perl metacharacter. So, this

@line = split /$char/, $_;
works when $char is 'z', but not when $char is '*'.

Quick workaround, anyone?

Replies are listed 'Best First'.
Re: Split on metachar
by saskaqueer (Friar) on Jan 06, 2005 at 01:19 UTC

    You are wanting the \Q usage within a regex/double-quoted string, which is the same as quotemeta():

    # this @time = split( /\Q$char/, $_ ); # or this $char = quotemeta( '*' ); @time = split( /$char/, $_ );
      Thanks to all for the quick and helpful replies.

      Quotemeta! Who knew?! (Not me, obviously.)

Re: Split on metachar
by Eimi Metamorphoumai (Deacon) on Jan 06, 2005 at 01:20 UTC
Re: Split on metachar
by borisz (Canon) on Jan 06, 2005 at 01:21 UTC
    use quotemeta or "\Q*".
    my $char = quotemeta '*'; # or "\Q*" instead of quotemeta @line = split /$char/, $_;
    Boris
Re: Split on metachar
by gopalr (Priest) on Jan 06, 2005 at 09:17 UTC

    Hi,

    you can solve this problem by two ways.

    1.way ---Using \Q and \E

    @line = split /\Q$char\E/, $_;

    2. way --- Using 'quotemeta'

    $a='abcdef*2dfd'; $char='*'; $char=quotemeta($char); @line=split/$char/, $a; print "@line";

    Thanks,

    Gopal.R