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

monks,

@array = ( "file1:aa" , "file2:bb" , "file3:cc" ); if ( grep ( /aa/i,@array) ) { print "Matched\n" }
the above code gives the output as 'Matched'. what should I need to do to get the output as 'Matched In file1:aa'?

Replies are listed 'Best First'.
Re: how to get the full array value if part of the element matches
by McDarren (Abbot) on Oct 20, 2006 at 04:23 UTC
    I think you want something like:
    my @matches = grep { $_ =~ /aa/i } @array; print "Matched:$_\n" for @matches;

    Cheers,
    Darren :)

      my @matches = grep { $_ =~ /aa/i } @array; print "Matched:$_\n" for @matches;

      Since the nature of the question itself clearly shows that the OP is a complete newbie, I think it may be worth to add that it's not necessary to pass through an intermediate @matches variable (before he cargo cults such an use), although in other cases it could, and in some others it may be convenient anyway:

      print "Matched:$_\n" for grep { $_ =~ /aa/i } @array;

      But wait! Here you have two loops, of which one implicit in grep, whereas one would suffice. Hence a solution like that of fenLisesi may be preferable, but (to the OP!) be warned that it doesn't really matter in terms of performance.

Re: how to get the full array value if part of the element matches
by davido (Cardinal) on Oct 20, 2006 at 04:27 UTC

    This may be what you're after:

    use strict; use warnings; my @array = ( "file1:aa" , "file2:bb" , "file3:cc" ); my( @found ) = grep { $array[$_] =~ m/aa/ } 0 .. $#array; print "Matched in $array[$_]\n" foreach @found;

    Update
    I wanted to point out that the difference between my implementation, and McDarren's is that his caches the elements from @array that matched, and mine caches the indices of the elements from @array that matched. It's up to you to decide which is better for you. There are subtle advantages to each.


    Dave

Re: how to get the full array value if part of the element matches
by fenLisesi (Priest) on Oct 20, 2006 at 06:45 UTC
    use strict; use warnings; my $MATCH_THIS = q(aa); my @filenames = qw(file1:aa file2:bb file3:cc file4:AA); for my $fn (@filenames) { print "Matched $fn\n" if $fn =~ /$MATCH_THIS/i; }
    prints:
    Matched file1:aa Matched file4:AA
    However, from the word 'In' in your post, I get the feeling that you want to grep the content of the files named aa, bb etc. That's not the case, is it?

    Update: Added "the content of" for clarification.
    Update: Changed @array to @filenames.