#!/usr/bin/perl

use 5.006;

use strict;
use warnings;

use File::Find;
use File::Spec;
use Getopt::Long;
use PPI;
use PPIx::Regexp;

my %opt;

GetOptions( \%opt, qw{ once! } ) or die;

find( \&interpolated, @ARGV ? @ARGV : ( File::Spec->curdir() ) );

sub interpolated {
    -d $_ and return prune();
    is_perl( $_ ) or return;
    my $named;
    my $doc = PPI::Document->new( $_ );
    foreach my $class ( qw{ PPI::Token::Regexp::Match
	PPI::Token::Regexp::Substitute
	PPI::Token::QuoteLike::Regexp
	} ) {
	foreach my $elem ( @{ $doc->find( $class ) || [] } ) {
	    my $re = PPIx::Regexp->new( $elem );
	    $re->regular_expression()->find_first(
		'PPIx::Regexp::Token::Interpolation' )
		or next;
	    $opt{once} and $re->modifier()->asserts( 'o' ) and next;
	    $named++ or print $File::Find::name, "\n";
	    print '    ', $re->content(), "\n";
	}
    }
}

sub is_perl {
    my ( $fn ) = @_;
    -T $fn or return;
    $fn =~ m/ [.] pm \z /smx  and return 1;
    $fn =~ m/ [.] pl \z /smxi and return 1;
    open ( my $fh, '<', $fn ) or return;
    local $_ = <$fh>;
    close $fh;
    defined $_ or return;
    m/ \A [#] ! .*? perl /smx and return 1;
    m/ \A [#] ! /smx and return;
    $fn =~ m/ [.] t  \z /smx  and return 1;
    return;
}

{

    my %pruned;
    
    BEGIN {
	%pruned = map { $_ => 1 } qw{ blib };
    }

    sub prune {
	'.' eq $_ and return;
	$pruned{$_}
	    or m/ \A [.] /smx
	    or return;
	$File::Find::prune = 1;
	return;
    }
}


__END__

=head1 TITLE

interpolated - Find all interpolated regular expressions

=head1 SYNOPSIS

 interpolated
 interpolated lib
 interpolated -once

=head1 OPTIONS

=over

=item -once

If this option is asserted, only interpolated regular expressions
B<without> the C</o> qualifier are found.

=back

=head1 DETAILS

This script searches files or directories for interpolated regular
expressions. These are considered to be matches or C<qr{ }> expressions
containing interpolations, or substitutions containing interpolations in
their regular expressions. Interpolation in the replacement portion of
the substitution are not considered.

The names of any files containing such regular expressions are listed,
along with the statements themselves.

If C<-once> is asserted, only regular expressions without the C</o>
modifier are listed.

=head1 AUTHOR

Thomas R. Wyant, III F<harryfmudd at comcast dot net>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2010-2023, 2025-2026 by Thomas R. Wyant, III

This program is free software; you can redistribute it and/or modify it
under the same terms as Perl 5.10.0. For more details, see the full text
of the licenses in the directory LICENSES.

This program is distributed in the hope that it will be useful, but
without any warranty; without even the implied warranty of
merchantability or fitness for a particular purpose.

=cut

# ex: set textwidth=72 :
