Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Braino - why is this not working?

by duelafn (Parson)
on Oct 18, 2010 at 22:46 UTC ( [id://866060]=note: print w/replies, xml ) Need Help??


in reply to Braino - why is this not working?

kcott is right

Your function fails here:

my $ans=grep /^$_$/, @res;

Which $_ are you matching $_ against? :)

Also, (not relevant in this example) you should protect metacharacters: /^\Q$_\E$/

Good Day,
    Dean

Replies are listed 'Best First'.
Re^2: Braino - why is this not working?
by perl-diddler (Chaplain) on Oct 19, 2010 at 00:58 UTC
    It's the $_ from the 'foreach' from the array that is passed.

    Array is passed in that has lines, say,
    aaa,
    bbb,
    ccc.

    Create empty array for results, is 'aaa' in it? No? add to results, next, is 'bbb' in results array? (well I just added 'aaa', and that's it, so results should be no, BUT results are 'yes').

    That's the problem.

    Why is 'bbb' in an array that only contains 'aaa'?

      It's the $_ from the 'foreach' from the array that is passed.

      The closes such construct is the map, not the foreach

      my @a = 1 .. 3; my @res = 0; for(@a){ my $ans = grep { warn ">>$_<< "; /^$_$/ } @res; warn "ans >>>$ans<<< " } __END__ >>0<< at - line 4. ans >>>1<<< at - line 8. >>0<< at - line 4. ans >>>1<<< at - line 8. >>0<< at - line 4. ans >>>1<<< at - line 8.
        Details slightly off, but the essence was it.

        Detail: the foreach works sets "$_" to each value in the list, in turn

        print "_=$_\n" for (1..3);
        but ...

        Your post hit the reason for the problem. "Grep" sets $_ to each member in turn, so searching for '$_' will always return 'true' if you search on /$_/;

        Absolutely simple, got caught with my 1 'register' var being double used. Sigh. Thinking about the simplicity of using $_ in 'foreach', I forgot about grep...sigh.

        MUCH thanks -- very it was driving me crazy!

Re: meta chars --
by perl-diddler (Chaplain) on Oct 19, 2010 at 04:35 UTC
    Something I need in the larger prog where this is from. Just hadn't gotten there yet, was expecting to have to use some 'quote::meta' cpan type function -- completely forgot about \Q\E -- (never have had the occasion to use them, till now... )...

    Thanks!

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://866060]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others pondering the Monastery: (5)
As of 2024-04-26 07:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found