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

Hi monks,

I have started to learn perl now only. I was trying to list and download files in my app which matches the perl regex which i give. Let's say we have 3 files
1) asdf 
2) efgh 
3) qwer 
The problem is i want to download all files except asdf. For this i got two ideas. one way is [^(asdf)]and the other way is  ^(?!asdf) I want to know the difference between both. Could some one please explain this ?
Thanks in advance,
Rookie696.

Replies are listed 'Best First'.
Re: understanding regex
by Athanasius (Archbishop) on Sep 08, 2013 at 06:19 UTC

    Hello rookie696, and welcome to the Monastery!

    In a regex, [^(asdf)] is a character class which says: match one character as long as that character is not a parenthesis or a lower-case ‘a’, ‘s’, ‘d’, or ‘f’. This is not what you want.

    ^(?!asdf) says: match the beginning of the line not followed by ‘asdf’. This will work, but it uses a negative look-ahead assertion which is overkill for your purpose.

    What you want is simply to negate a normal match. For example:

    my @files = ...; for my $file (@files) { download($file) unless $file =~ /^asdf/; }

    Or, equivalently,

    for my $file (@files) { download($file) if $file !~ /^asdf/; }

    You should read up on regexes. Here are some good references:

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

Re: understanding regex
by rjt (Curate) on Sep 08, 2013 at 17:37 UTC

    To add to the excellent advice by Athanasius, now would also be a good time to learn about grep:

    my @downloads = grep { !/^asdf$/ } @file_list; print "Downloading: @downloads\n";

    It's also worth noting that if you truly want to exclude a literal string, you don't need a regex at all, so you could also do:

    my @downloads = grep { $_ ne 'asdf' } @file_list;

    This works just as well if asdf is in a variable.

    my $exclude = 'asdf'; # Maybe user input or other program logic my @downloads = grep { $_ ne $exclude } @file_list;
    use strict; use warnings; omitted for brevity.