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

Hi Monks, I make a dumb typo while looping through a match. I did end up with an interesting result. I was wondering if someone could tell me what the mistake is doing? What I meant to do was loop through a folder and grab certain .htm files... as such:
my @files = <*.HTM>; foreach $file (@files) { if ($file =~ m/IDX/gi){print $file."\n";} }
Which results in:
ACIDX.HTM APIDX.HTM ...
What I did instead was (note the ~ placement) this:
my @files = <*.HTM>; foreach $file (@files) { if ($file = ~m/IDX/gi){print $file."\n";} }
Which results in:
4294967295 4294967295 ...
What is my mistake doing?

Replies are listed 'Best First'.
Re: Interesting Mistake
by cdarke (Prior) on Feb 22, 2010 at 15:37 UTC
    The tilde ~ is a unary bitwise operator to negate the bits (ones complement), see perlop.

    The actual number returned is all bits set:
    printf "0%08x\n",4294967295;
    Gives: 0ffffffff

    m returns 0 on a failure to match:
    printf "0%08x\n",~0;
    also gives 0ffffffff.

    Updated to explain more.
Re: Interesting Mistake
by FunkyMonk (Bishop) on Feb 22, 2010 at 15:46 UTC
    m/IDX/ returns true (1) if $_ matches the pattern and false otherwise. ~ is the bitwise not operator (aka one's complement - see Symbolic Unary Operators). It inverts all the bits in a number.

    Your match doesn't match $_ and so returns false, which is complemented to 0xffffffff, which, in decimal, prints as 4294967295.

    Try

    perl -e 'print ~0'
    or, for 64-bit perl:

    perl -e 'print ~0 & 0xffffffff'

    Update: Added code examples & link to ~ in perlop

Re: Interesting Mistake
by toolic (Bishop) on Feb 22, 2010 at 15:48 UTC
    What is my mistake doing?
    In addition to what cdarke said, you should use strict and warnings, which would warn you that something is wrong.

    =~ is one of the Binding Operators, but = ~ are two separate operators (= and ~). You are assigning the value of the ~m/IDX/gi to the $file variable. Since the assignment succeeds, you print the variable's value.

Re: Interesting Mistake
by biohisham (Priest) on Feb 22, 2010 at 15:58 UTC