in reply to how to get the String as regularexpression

This doesn't really answer your question, but you may want to check out File::Find which addresses this problem space.

I'm not sure what problem you are having with the use of a scalar as a regex -- the following code snippet seems to work for me:

use strict; use warnings; my $exten = "(\\\.txt|\\\.csv)"; my @files = ('one.txt', 'two.html', 'three.csv', 'four.log'); foreach (@files) { if (/$exten/i) { print $_, "\n"; } }

... and the output:

one.txt three.csv

Update: I concur with prasadbabu below, in that the judicious use of anchors can help your regex be more faithful to your intentions. Also, as davorg has noted, the main problem with your regex was the leading '|' character (which I assumed was a typo). As you probably know, the pipe character serves the function of 'or' within a regex.

Update 2: Fixed problem with backslashes and case insensitivity, as noted by ikegami. I wasn't sure about the OP's intention, so left out the anchor deliberately.


No good deed goes unpunished. -- (attributed to) Oscar Wilde

Replies are listed 'Best First'.
Re^2: how to get the String as regularexpression
by ikegami (Patriarch) on Oct 03, 2006 at 15:24 UTC

    Your code will also match a file named pretxt.
    my $exten = "(\.txt|\.csv)";
    should be
    my $exten = "(\\\.txt|\\\.csv)";  # (\.txt|\.csv)

    There's no reason to force the user to specify the parens.
    Why did you remove the case-insensitivity?
    You also forgot to anchor the regexp.

    use strict; use warnings; my $exten = "\\\.txt|\\\.csv"; # \.txt|\.csv my @files = qw( one.txt two.html three.csv four.log pretxt file.txt~ File.Txt ); foreach (@files) { if (/($exten)\z/i) { print $_, "\n"; } }

    Update: Or if you want to build $exten:

    my @exten = qw( .txt .csv ); my $exten = join('|', map quotemeta, @exten);