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

Hi every 1
I know this sound like a mostly theoretical "I wondered" question,
but I actually got a practical reason (long to explain) to ask this:
is there a value of $reg which will return true by $emp =~ /$reg/;
when and only when $emp is an empty string ?

Thx

Update:
My personal definition of an empty string is zero-length.
Technically it doesn't include undef, as it isn't a string, but its irrelevant for my use.

Update: problem resolved.
It seems to me that ^\z and \A\z function the same way,
but as \z seems better than $ for this purposeת>נר< I'll assume the same for their counterparts and go with \A\z over ^\z.
(unless one of you will find another loophole ^^)

But regardless thanks all around :]

Replies are listed 'Best First'.
Re: Is there a regex match for an empty string ?
by GrandFather (Saint) on Mar 19, 2012 at 23:21 UTC

    Define "empty string". Consider:

    use strict; use warnings; for my $str ('', ' ', '\0', "\n", undef) { print "matched '$str'\n" if $str =~ /\A\z/; }

    Prints:

    matched '' Use of uninitialized value $str in pattern match (m//) at C:\Users\Pet +er\Delme~~\PerlScratch\noname.pl line 8. matched '' Use of uninitialized value $str in concatenation (.) or string at C:\U +sers\Peter\Delme~~\PerlScratch\noname.pl line 8.

    length may be a better test than using a regex, and clearer to the maintenance programmer.

    True laziness is hard work
      I agree with you that the "length" function is the better solution,
      but I'm bounded by a generalized format, which requires regex.
Re: Is there a regex match for an empty string ?
by CountZero (Bishop) on Mar 19, 2012 at 23:16 UTC
    /^$/

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

    My blog: Imperial Deltronics

      or better /^\z/   (as /^$/ also matches "\n", which is not an empty string).

    A reply falls below the community's threshold of quality. You may see it by logging in.