Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re: Regex issues

by TomDLux (Vicar)
on Jul 13, 2013 at 05:16 UTC ( [id://1044121] : note . print w/replies, xml ) Need Help??

in reply to Regex issues

I dislike using regexes when simple string functions can handle the job.

By extracting the magic delimiter characters into a predefined constant, the code is clearer and more easily extendable. split will partition an input string on any of those special characters, and the wrapper (xx)[0] extracts the first element from the resulting list.

my @DELIMS = (qw( _ @ )); for my $elem ( @inputs ) { push @result, ( split /[@DELIM]/, $elem )[0]; }

As Occam said: Entia non sunt multiplicanda praeter necessitatem.

Replies are listed 'Best First'.
Re^2: Regex issues
by AnomalousMonk (Archbishop) on Jul 13, 2013 at 13:05 UTC
    my @DELIMS = (qw( _ @ )); ... ... /[@DELIM]/ ...

    If the default value of  $" is unchanged, the array  @DELIMS will be interpolated into the regex character class with an extraneous space character, which is then a valid part of the class: a bug waiting to happen. Locally set  $" to the empty string or, better yet, use join to form the char class string.

    >perl -wMstrict -le "my @DELIMS = (qw( _ @ )); ;; my $rx = qr{[@DELIMS]}; print $rx; ;; { local $\" = ''; $rx = qr{[@DELIMS]}; } print $rx; ;; my $cc = join '', @DELIMS; $rx = qr{[$cc]}; print $rx; " (?^:[_ @]) (?^:[_@]) (?^:[_@])

    Do not multiply bugs without necessity!

Re^2: Regex issues
by Anonymous Monk on Jul 13, 2013 at 08:02 UTC

    ... I dislike using regexes..
    But your usage of "split" ... split /[@DELIM]/, $elem .. is still regexes...
    Or you say otherwise?