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

hi, I am trying to search between pattern and prefix for each line of the resultset. But it doesnt work. Please help. New to perl.
perl -ne 's/^/ $i $j /g && print if /START $i/ .. /END $j/ ' file
Thank you

Replies are listed 'Best First'.
Re: Search between pattern and append
by Corion (Patriarch) on Jul 13, 2018 at 14:41 UTC

    What does your input look like? What are the values of $i and $j?

    How does your program fail?

      START $i MAY JUNE JULY END $j
      here $i and $j are variables which change. I am trying to search (with a one liner) between the pattern1 and pattern2 and prefix a variable.
      perl -ne ' print if /START $i/ .. /END $j/' file.txt
      EXPECTED RESULT:
      START $i $i $j MAY $i $j JUNE $i $j JULY END $j
      The $i and $j values change with variable
Re: Search between pattern and append
by Marshall (Canon) on Jul 13, 2018 at 17:27 UTC
    Why does this have to be a "one-liner"?.
    Why not code something simple? Is this some kind of "golf" test?
    #!/usr/bin/perl use strict; use warnings; while (<DATA>) { process_record ($1) if /^\s*START\s*(\w+)/; } sub process_record { my $start_value = shift; my @record; my $line; while (defined ($line=<DATA>) and $line !~ /^\s*END/) { push @record, $line; } my ($end_value) = $line =~ /^\s*END\s+(\w+)/; @record = map{"$start_value $end_value $_"}@record; print @record; print "\n"; } =prints abc xyz MAY abc xyz JUNE abc xyz JULY oue 2345 MAY oue 2345 JUNE oue 2345 JULY =cut __DATA__ START abc MAY JUNE JULY END xyz blah ....more blah... START oue MAY JUNE JULY END 2345
    Update: I looked back upon this thread and these 2 lines could have been better written. I don't remember why I did what I did in the original coding. I do remember that I wrote the code in an attempt to get the OP "unstuck" and was surprised at the "one liner" requirement. Anyway the OP obviously doesn't care about this, but other future readers might...However, I will add that in this sort of situation, the difference probably doesn't matter at all...
    # @record = map{"$start_value $end_value $_"}@record; # print @record; print "$start_value $end_value $_" for @record;
      Can you advice in a one liner ?
        Yes, it is possible that I could devise a "one-liner", but WHY?
        I can also write code use the flip-flop operator, but WHY?
        Your situation is not the ideal case for the flip-flop.

        There is significant overhead in invoking Perl. There is no difference if the Perl program is expressed as one line or 20 lines.

        Why are you obsessed with a "one-liner" solution? This has no performance basis.

        Does my code accomplish your desired behaviour? If not, then why not?