http://www.perlmonks.org?node_id=11103963

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

Greetings! I just registered here and hope this is an appropriate venue for my question.

I'm new to perl and am trying to write a perl one-liner that returns everything from the first non-indented line of a file up until the end of that paragraph, terminated by a blank line. I can do this using awk with the command:

awk -v RS='' -v ORS='\n\n' '/^[^ ].*$/' file.txt | awk -v RS='' 'NR==1 +{print $0}'
My problem translating this to perl is that the first non-indented line of the file may or may not be the first line of the file. In the former case, this works:
perl -0pe 's/.*?\n*?([^ \n].*?)\n\n.*/$1/gs' file.txt
as does this:
perl -0pe 's/([^ \n].*?)\n\n.*/$1/gs' file.txt
In the latter case, this works:
perl -0pe 's/.*?\n([^ \n].*?)\n\n.*/$1/gs' file.txt
But is there a simple perl one-liner that works in both cases? I've tried writing a semicolon-separated perl command intended to prepend a blank line to the file before the search in the event that the first line is not indented, using something like
if ( $. == 1 and /^[^ ].*$/ ) {...}
but I can't get the syntax right. Obviously I could string together a sequence of commands like
echo '' > tempfile.txt ; cat file.txt >> tempfile.txt ; perl ...
or use some bash conditional like
if [[ $(egrep -n -m1 -e '^[^ ]' file.txt | sed 's/^\([0-9]\+\):.*/\1/g +') -eq 1 ]] ; then perl ... ; else perl ... ; fi
however, I'd like to know if there's some more elegant "pure perl" solution I'm overlooking.

Best regards,

Maneesh