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

Hi with this code I find all the strings matching in the whole database. what I am looking for is finding the first exact occurence of the string and printing the line under that. e.g
colours red blue yellow
I want to search for coulours and have the whole block as a result. thanks
#!/usr/local/bin/perl use strict; my $file = 'thesaurus'; # Name the fil +e open(INFO,$file) || die "Cannot open file"; # open the fil +e or say can't open file # Read it in +to an array print " what are you looking for? "; $a = <STDIN>; chomp $a; # get rid of a + new line while (<INFO>){ if($file eq "\n"){ last; } my @matches = grep {/$a/i} <INFO>; # find all +the matches print "The following matches were found: @matches\n"; # print th +e matches }

Replies are listed 'Best First'.
Re: pattern matching
by runrig (Abbot) on Dec 01, 2000 at 21:41 UTC
    This looks like the same question that was in limbo in Q&A, and now seems to have disappeared. Here's my answer from there:
    #!/usr/local/bin/perl -w use strict; while (<DATA>) { if (my $status=/^Colours$/.../^\S/) { last if $status =~ /E0/; print; } } __DATA__ Flavours sweet sour Colours orange yellow red MoreAttributes stuff
Re: pattern matching
by mrmick (Curate) on Dec 01, 2000 at 19:48 UTC
    This is assuming that you are looking for an exact match on the entire line. If not, then you can get rid of the leading ^ and $ .
    #!/usr/local/bin/perl use strict; my $file = 'thesaurus'; # Name the file # get this into an array unless the file is too big open(INFO,$file) || die "Cannot open file"; my @lines = <INFO>; close(INFO); print " what are you looking for? "; $a = <STDIN>; chomp $a; my $found = 0; foreach(@lines){ # get the match if($found == 0){ chomp; if(/^$a$/){$found = 1;} } # print the next line else{ print; } }
    Hope this helps....

    Mick
Re: pattern matching
by marvell (Pilgrim) on Dec 01, 2000 at 19:29 UTC
    Are the blocks delimited in any way? You ask for "the line under that" in the first section, and "the block" in the second. Do you have an example file?

    --

    Brother Marvell