in reply to using split without $junk

Maybe you don't want split at all. How about:

my $string = "Keep this | toss this"; my ( $keep ) = $string =~ /^(.*?)\|/; print $keep, "\n";

Update: On the other hand, if you really do need split (for example, because your list of things you're keeping is pretty long), you should just constrain split with the 3rd argument, and do something like this:

my $string = "keep this | keep that too | toss this | toss this too"; my ( $this, $that ); ( $this, $that, undef ) = split /\|/, $string, 3;

You don't have to explicitly list "undef", but in some cases, it makes the code more understandable if you have to go back and look at it again in a month.


Dave


"If I had my life to live over again, I'd be a plumber." -- Albert Einstein

Replies are listed 'Best First'.
Re: Re: using split without $junk
by jeffa (Bishop) on Nov 24, 2003 at 18:48 UTC
    my ( $keep ) = $string =~ /^(.*?)\|/;
    Because you know where you want to stop matching, you really should drop .* and use a negated character class instead:
    my ( $keep ) = $string =~ /^([^\|]+)/;

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    B--B--B--B--B--B--B--B--
    H---H---H---H---H---H---
    (the triplet paradiddle with high-hat)
    
      I agree, and actually originally had it as [^|]+ ( | isn't special inside character classes, IIRC). But after hitting "preview" decided that the negated character class method might seem unclear to the OP, so I changed it to the more ubiquitous .*?.

      But your point is valid, that .* and .+ are usually the lazy, slower, and more prone to mistakes ways to do things in pattern matching.


      Dave


      "If I had my life to live over again, I'd be a plumber." -- Albert Einstein