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

have the below code, and its input file "fruits.txt" has following values.

Apple Mango Grapes Bananas Avocado

I'm getting the output as below;

Grapes not in list Strawberry not in list Grapes not in list Strawberry not in list Grapes Strawberry not in list Grapes not in list Strawberry not in list Grapes not in list Strawberry not in list Grapes not in list Strawberry not in list

However, i'm actually looking for an output like this, please help!

Expected result as follows.

Grapes Strawberry not in list
use strict; use warnings; open (FILE,"fruits.txt"); while (<FILE>) { if (/Grapes/) { print $_; } else { print "Grapes not in list\n";} if (/strawberry/i) { print $_; } else { print "Strawberry not in list\n"; } } close FILE;

2018-03-23 Athanasius added code tags

Replies are listed 'Best First'.
Re: Print only the matched line when process line by line from a file
by davido (Cardinal) on Mar 21, 2018 at 19:10 UTC

    So the question is how to put more than one condition into the initial if()?

    if (/Grapes/ || /strawberry/i) { print; } else { print "$_ is not in the list.\n"; }

    Or in this case you could leverage the power of alternation within the regular expression:

    if (/Grapes|(?i:strawberry)/) { .... } else { .... }

    If the behavior is supposed to differ based on what matched, you could also do this:

    if(/foo/) { # do something } elsif (/bar/) { # do something else } else { # complain about falling through }

    Dave

Re: Print only the matched line when process line by line from a file
by NetWallah (Canon) on Mar 21, 2018 at 20:49 UTC
    Since the OP wants both positive and negative answers for list membership, I would go with a hash:
    my %looking_for = (Grapes=>0, strawberry=>0); #Inside file read loop: for my $fruit (keys %looking_for){ next unless m/$fruit/i; $looking_for{$fruit}++; } #-- At end of program.. for my $fruit (sort keys %looking_for){ print $fruit, ($looking_for{$fruit} ? "" : " not in list"), "\n"; }

                    Python is a racist language what with it's dependence on white space!

Re: Print only the matched line when process line by line from a file
by stevieb (Canon) on Mar 21, 2018 at 19:13 UTC

    Please, when you cross-post on different sites, it is considered polite to inform all locations that you've done so.

Re: Print only the matched line when process line by line from a file
by BillKSmith (Monsignor) on Mar 21, 2018 at 22:28 UTC
    It is impossible to know that a fruit is not in the file until you have read the entire file. NetWallah has proposed a program that saves (but does not print) the required data as you read the file. After all the data is collected, you can decide what to print.
    Bill
A reply falls below the community's threshold of quality. You may see it by logging in.