in reply to copy line with character

Hi jalopez453, welcome to the Monastery!

When asking a question of PerlMonks, please provide us some of your sample input data, and what your expected output would look like (both in <code></code> tags as you've done with your actual code).

I suspect what you're getting as output are all lines that contain M, but anywhere in the string, not just at the beginning. What you need to do is specify in your regex that you ONLY want to match if an M is at the start of your string. You do this by using the caret, aka ^ at the beginning of your regex:

my $find = '^M';

After that change is made, using this data:

no M at start M at start M at start again another line, no M at start

I get this output:

M at start M at start again

Replies are listed 'Best First'.
Re^2: copy line with character
by jalopez453 (Acolyte) on Nov 23, 2015 at 18:54 UTC

    Sorry about that. For the next questions I have I will remember to include a sample of my input file. Thank you so much for the quick response this is exactly what I was wanting to accomplish!

      If you are still available, I do have another question? :) If I want to include the second line after the line containing M and wrap it all into one line on the output file what would I have to include?

      sample of input file: M12345678 John Doe 11/20/15 M987654 REJECTED FAILED --------------------------------------------- sample of output file: M12345678 John Doe 11/20/15 M987654 REJECTED FAILED use strict; my $find = '^M'; open (NEW, ">", "output.txt" ) or die "could not open:$!"; open (FILE, "<", "Report.txt") or die "could not open:$!"; while (<FILE>) { print NEW if (/$find/); } close (FILE); close (NEW);

        You can use a variable to check whether you've made a match on the previous line or not, then reset it back to zero when you hit one (ie. printed the 2nd line). Note how the check for $match and the subsequent printing of the 2nd line is done before looking for $find and printing the first...

        my $match = 0; while (<FILE>) { # get rid of newlines chomp; if ($match){ # we have a line to print; reset the counter $match = 0; # replace multi-spaces with a single one s/\s+/ /g; print NEW "$_\n"; } if (/$find/){ # we found a $find; set $match to true $match = 1; print NEW $_; } }

        I'd recommend that you use lexical (variable-based) file handles instead of bareword handles though. BAREWORD handles are global, whereby variable based ones are lexical to the scope they're defined in, and can be passed around in subroutine calls:

        open my $fh, '<', 'Report.txt' or die "can't open the damned Report.txt file!: $!";
        Your sample is too small to tell if this would work. You may be able to greatly simplify your code by defining the special variable $RECORD_INPUT_SEPARATOR ($/) to redefine 'line' as a 'logical block' of input. See perlvar
        Bill