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

I want to print only particular lines. For that I wrote like this. But its writing all the lines.

#!/usr/bin/perl # use strict; use warnings; use List::MoreUtils qw(any uniq); my @line_numbers = (1,2,5,6,9,10,18,19,23,24,25,30,31,33); my $line_number = 0; foreach my $li (1..35) { if (any {$line_number} @line_numbers) { print "$line_number :\n"; } $line_number++; }

Where am I missing??//

Replies are listed 'Best First'.
Re: Problem in "any"
by poj (Abbot) on Jan 23, 2016 at 13:42 UTC
    Where am I missing?

    You need a criteria

    any BLOCK LIST
    
    Returns a true value if any item in LIST meets the criterion given through BLOCK. Sets $_ for each item in LIST in turn:
    
    if (any {$line_number == $_} @line_numbers){
    poj
Re: Problem in "any"
by choroba (Cardinal) on Jan 23, 2016 at 13:46 UTC
    In the curly braces after any, you must specify a code that returns true or false. $line_number returns false only in the first iteration of the loop when it's zero, and stays true afterwards. Moreover, you don't need $line_number, you already have the $li variable that can serve its purpose:
    #!/usr/bin/perl use warnings; use strict; use List::MoreUtils qw{ any }; my @line_numbers = (1, 2, 5, 6, 9, 10, 18, 19, 23, 24, 25, 30, 31, 33) +; for my $line_number (1 .. 35) { if (any { $_ == $line_number } @line_numbers) { print "$line_number :\n"; } }

    But for the same output, you can just use

    print map "$_ :\n", @line_numbers;

    Instead of the for loop.

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
Re: Problem in "any"
by Anonymous Monk on Jan 23, 2016 at 13:44 UTC

    In any BLOCK LIST, the thing in the BLOCK needs to be a condition that tests against $_, which is set to each item of the LIST, @line_numbers, until a match is found. Change it to {$_==$li}, I am guessing that's the result you're looking for?