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

How can I get the following to work?

$delimiter = "|"; @list = split $delimiter, $line;
I've read as much as I could find about split() but,
I can't find anything about using a variable in "/PATTERN/"
Perldoc sais that  /$delimiter/o should work
but, it wont for me.

Thanks for any help folks.

Replies are listed 'Best First'.
Re: split question
by Limbic~Region (Chancellor) on Jan 30, 2004 at 22:40 UTC
    Anonymous Monk,
    In this case, your pipe symbol is also a metacharacter. The following should work:
    $delimiter = '|'; $delimiter = quotemeta $delimiter; @list = split /$delimiter/ , $line;
    Cheers - L~R

    Update:
    Of course this is overkill - you could just escape it with a backslash. It just demonstrates how you would escape all metacharacters if they were not known ahead of time.

      Of course this is overkill - you could just escape it with a backslash.

      I don't think it's overkill. Look carefully at the OP's code. If you'd told him just to back-whack his pipe, he probably would've repsonded with "that didn't work either" because he probably would have done $delimiter = "\|";

      I think your response was just perfect. If only I'd hit the "create" button on my reply immediately rather than doing Real Work instead I'd've been first! Now I'm just lost in the shuffle ;-)

      Yes, If I knew it ahead of time, this would be overkill.
      But, your idea worked like a charm.

      Thanks much!
Re: split question
by b10m (Vicar) on Jan 30, 2004 at 22:42 UTC

    This seems to work:

    use Data::Dumper; $line = "foo|bar"; $delimiter = '\|'; @list = split($delimiter, $line); print Dumper @list;

    Producing this output:

    $VAR1 = 'foo'; $VAR2 = 'bar';
    --
    b10m

    All code is usually tested, but rarely trusted.
Re: split question
by duff (Parson) on Jan 30, 2004 at 22:47 UTC

    It's helpful to remember that the first parameter to split will always be treated as a regular expression (with the one exception of " "). Variables work fine in regular expressions and are expanded before the expression is evaluated, so your code boils down to @list = split "|", $line;. Since the pipe symbol (|) is special in regular expressions, you need to escape it. This is typically done with quotemeta

Re: split question
by allolex (Curate) on Jan 30, 2004 at 22:41 UTC

    The pattern is a regular expression pattern. ;)

    split /\|/, $line;

    have a look at perldoc -f split (split) and perlre.

    --
    Allolex

    Update Sat Jan 31 05:05:13 2004: Added slashes. I saw that particular syntax on comp.lang.perl.misc, and just assumed that it would work (mea maxima culpa).

      split \|, $line;

      Huh? Try:  split /\|/, $line;

      You forgot your quote-like regexp characters.

      Or to answer the OP's question:

      my $delimiter = quotemeta( '|' ); my @array = split /$delimiter/, $line;


      Dave