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

Hi Monks ! i am brand new to Perl, and i am currently struggling a bit with a question i have, but let me come to the point
i do have a Variable called $cmdout which is filled with some multiple lines of a console output, now i would like to search in this output for some words, and return the complete line where the word has been found. Example:
$cmdout = "Hello i like Perlmonks.org "; $search = $cmdout,/Perlmonks.org/;
at the moment i am getting only a True or false back, but i would like to have the $search filled with the complete line .
Any Ideas ?
Thanks

Replies are listed 'Best First'.
Re: Returning Line where Characters Have been found
by toolic (Bishop) on Dec 13, 2011 at 14:12 UTC
    You could use regular expressions, perldoc perlre:
    use warnings; use strict; my $search; my $cmdout = "some words\nHello i like Perlmonks.org \n more words"; if ($cmdout =~ / \n ( .* Perlmonks\.org .*) \n /sx) { $search = $1; print "$search\n"; } __END__ Hello i like Perlmonks.org
    A reply falls below the community's threshold of quality. You may see it by logging in.
Re: Returning Line where Characters Have been found
by pvaldes (Chaplain) on Dec 13, 2011 at 16:03 UTC

    And you can also use grep for this

    @lines_with_my_pattern = grep(/my_pattern/, @all_lines);
Re: Returning Line where Characters Have been found
by TJPride (Pilgrim) on Dec 13, 2011 at 14:25 UTC
    Two ways to do it:

    use strict; use warnings; my $cmdout = join '', <DATA>; while ($cmdout =~ /^(.*?lines.*?)$/mg) { print "$1\n"; } my @cmdout = split /\n/, $cmdout; for (@cmdout) { print "$_\n" if m/lines/; } __DATA__ my multiple lines of data go here and here are some more lines of data
      Hi TJ, thanks for your ideas here, but sadly i am a bit too stupid to understand what you have written there, i a struggling with the < DATA > part ..

        The __DATA__ segment at the end of the file stores data in what Perl interpretes as some sort of pseudo-file. To read that out, you can use the filehandle DATA.

        What TJPride does here is reading out all the lines as array and joining them into a single string. (Reading from < DATA > in array context since it is the array argument to join).

        BREW /very/strong/coffee HTTP/1.1
        Host: goodmorning.example.com
        
        418 I'm a teapot
        my $cmdout = join '', <DATA>; is the same as if I just put all the stuff below the __DATA__ line into $cmdout directly. It's also the same as if I had that data in a file, opened a filehandle to it (let's say FH) and then read it using my $cmdout = join '', <FH>;. Basically, __DATA__ is just a good way to post code examples without having to exclude the file data it's running on.