my $re_single = qr/ (?:\A|[\r\n]) # either the start of text or newline ( [^\r\n]* # any non-newlines (?:\z|(?:\r\n|\n\r|\r|\n)\z) # last newline or eof ) /xs; sub Last_N_Lines { my ( $str, $n ) = @_; my $nless = ( $n - 1 ); my $re_multiple = qr/ (?:\A|[\r\n]) # either the start of text or newline ( (?: [^\r\n]* (?:\r\n|\n\r|\r|\n) ){0,$nless} ) # have to enclose above so it all goes into $1 ( [^\r\n]* (?:\z|(?:\r\n|\n\r|\r|\n)\z) # last nl or eof ) /xs; if ( $n > 1 ) { if ( $str =~ m/$re_multiple/ ) { return( "$1$2" ); } else { return( "" ); } } if ( $str =~ m/$re_single/ ) { return( $1 ); } else { return( "" ); } }