App-Greple
view release on metacpan or search on metacpan
script/greple view on Meta::CPAN
--all print entire data
-F, --filter use as a filter (implies --all --need=0 --exit=0)
-m, --max=n[,m] max count of blocks to be shown
-A,-B,-C [n] after/before/both match context
--join remove newline in the matched part
--joinby=string replace newline in the matched text with a string
--nonewline do not add newline character at the end of block
--filestyle=style how filenames are printed (once, separate, line)
--linestyle=style how line numbers are printed (separate, line)
--blockstyle=style how block numbers are printed (separate, line)
--separate set filestyle, linestyle, blockstyle "separate"
--format LABEL=... define the format for line number and file name
--frame-top top frame line
--frame-middle middle frame line
--frame-bottom bottom frame line
FILE
--glob=glob glob target files
--chdir=dir change directory before search
--readlist get filenames from stdin
COLOR
--color=when use terminal colors (auto, always, never)
--nocolor same as --color=never
--colormap=color R, G, B, C, M, Y, etc.
--colorsub=... shortcut for --colormap="sub{...}"
--colorful use default multiple colors
--colorindex=flags color index method: Ascend/Descend/Block/Random/Unique/Group/GP
--random use a random color each time (--colorindex=R)
--uniqcolor use a different color for each unique string (--colorindex=U)
--uniqsub=func preprocess function to check uniqueness
--ansicolor=s ANSI color 16, 256 or 24bit
--[no]256 same as --ansicolor 256 or 16
--regioncolor use different color for inside and outside regions
--face enable or disable visual effects
BLOCK
-p, --paragraph enable paragraph mode
--border=pattern specify a border pattern
--block=pattern specify a block of records
--blockend=s block-end mark (Default: "--")
--join-blocks join consecutive blocks that are back-to-back
REGION
--inside=pattern select matches inside of pattern
--outside=pattern select matches outside of pattern
--include=pattern limit matches to the area
--exclude=pattern limit matches to outside of the area
--strict enable strict mode for --inside/outside --block
CHARACTER CODE
--icode=name input file encoding
--ocode=name output file encoding
FILTER
--if,--of=filter input/output filter command
--pf=filter post-process filter command
--noif disable the default input filter
RUNTIME FUNCTION
--begin=func call a function before starting the search
--end=func call a function after completing the search
--prologue=func call a function before executing the command
--epilogue=func call a function after executing the command
--postgrep=func call a function after each grep operation
--callback=func callback function for each matched string
OTHER
--usage[=expand] show this help message
--version show version
--exit=n set the command exit status
--norc skip reading startup file
--man display the manual page for the command or module
--show display the module file contents
--path display the path to the module file
--error=action action to take after a read error occurs
--warn=type runtime error handling type
--alert [name=#] set alert parameters (size/time)
-d flags display info (f:file d:dir c:color m:misc s:stat)
=cut
my @baseclass = qw( App::Greple Getopt::EX );
my $rcloader = Getopt::EX::Loader
->new(BASECLASS => \@baseclass);
my @optargs;
my %optargs;
sub newopt {
push @optargs, pairmap {
local $_ = $a;
s/\s+//g;
s/^(?=\w+-)([-\w]+)/$1 =~ tr[-][_]r . "|$1"/e; # "a-b" -> "a_b|a-b"
/^(\w+)/ and $optargs{$1} = $b if ref $b ne 'CODE';
$_ => $b;
} @_;
}
sub opt :lvalue {
my $name = shift;
my $var = $optargs{$name} or die "$name: invalid option name\n";
if (ref $var eq 'SCALAR') {
return $$var;
} elsif (ref $var eq 'HASH' and @_ == 1) {
return $var->{+shift};
} else {
return $var;
}
}
my @opt_pattern;
sub opt_pattern {
push @opt_pattern, [ map "$_", @_ ];
$opt_pattern[-1];
}
my @opt_colormap;
sub opt_colormap { push @opt_colormap, $_[1] }
sub opt_colorsub { push @opt_colormap, "sub{ $_[1] }" }
my %opt_format = (LINE => '%d:', FILE => '%s:', BLOCK => '%s:');
my %opt_alert = (size => 512 * 1024, time => 2);
my %opt_warn = (read => 0, skip => 1, retry => 0, begin => 0);
newopt
##
## PATTERN
script/greple view on Meta::CPAN
PROGRESS => "B",
TOP => "",
MIDDLE => "",
BOTTOM => "",
);
our @colors;
use Getopt::EX::Colormap;
my $color_handler = Getopt::EX::Colormap
->new(HASH => \%colormap, LIST => \@colors)
->load_params(@opt_colormap);
my @default_color =
$opt_ansicolor eq '16'
? qw(RD GD BD CD MD YD)
: qw(000D/544 000D/454 000D/445
000D/455 000D/545 000D/554
000D/543 000D/453 000D/435
000D/534 000D/354 000D/345
000D/444
000D/433 000D/343 000D/334
000D/344 000D/434 000D/443
000D/333)
;
if ($color_handler->list == 0) {
$color_handler->append
($opt_colorful ? @default_color : $default_color[0]);
}
if ($opt_ansicolor eq '24bit') {
no warnings 'once';
$Getopt::EX::Colormap::RGB24 = 1;
}
for my $opt (@opt_face) {
while ($opt =~ /(?<mk>[-+=]) (?<s>[^-+=]*) | (?<s>[^-+=]+) /xg) {
my($mk, $s) = ($+{mk} // '', $+{s});
for my $c (@colors) {
if ($mk eq '-') {
$c =~ s/[\Q$s\E]//g if $s ne '';
} elsif ($mk eq '=') {
$c = $s;
} elsif ($s ne '') {
$c .= "^" if $c ne '';
$c .= $s;
}
}
}
}
my $need_color = (($opt_color eq 'always')
or (($opt_color eq 'auto') and (!$opt_o and -t STDOUT)));
if (!$need_color) {
$Getopt::EX::Colormap::NO_COLOR = 1;
}
my %_esc = ( t => "\t", n => "\n", r => "\r", f => "\f" );
sub expand_escape {
$_[0] =~ s{\\(.)}{$_esc{$1} // $1}egr;
}
$_ = expand_escape($_) for values %opt_format;
my $blockend = "--";
if (defined $opt_blockend) {
$blockend = expand_escape($opt_blockend);
}
my $_file = sub { $color_handler->color('FILE' , sprintf($opt_format{FILE}, $_[0])) };
my $_line = sub { $color_handler->color('LINE' , sprintf($opt_format{LINE}, $_[0])) };
my $_block = sub { $color_handler->color('BLOCK', sprintf($opt_format{BLOCK}, $_[0])) };
my $_text = sub { $color_handler->color('TEXT' , $_[0]) };
my $_blockend = $color_handler->color('BLOCKEND', $blockend);
my $_top = $color_handler->color('TOP' , $opt_frame_top);
my $_middle = $color_handler->color('MIDDLE' , $opt_frame_middle);
my $_bottom = $color_handler->color('BOTTOM' , $opt_frame_bottom);
sub index_color {
$color_handler->index_color(@_);
}
sub color {
$color_handler->color(@_);
}
my $uniq_color = UniqIndex->new(
ignore_newline => 1,
prepare => \@opt_uniqsub,
);
sub dump_uniqcolor {
my $list = $uniq_color->list;
my $count = $uniq_color->count;
for my $i (keys @$list) {
warn sprintf("%3d (%3d) %s\n",
$i, $count->[$i],
index_color($i, $list->[$i]));
}
}
# --colorindex
my %color_index = map { uc $_ => 1 } $opt_colorindex =~ /\w/g;
my $indexer = do {
if ($color_index{S}) {
@colors = shuffle @colors;
}
if ($color_index{A} or $color_index{D}) {
my $i = 0;
Indexer->new(
index => sub { $i++ },
reset => sub { $i = 0 },
block => $color_index{B},
reverse => $color_index{D},
);
}
elsif ($color_index{R}) {
Indexer->new(index => sub { int rand @colors });
}
else { undef }
};
my $opt_uniqcolor = $color_index{U};
# -dc
if ($opt_d{c}) {
my $dump = sub {
local $_ = Dumper shift;
script/greple view on Meta::CPAN
to use direct index, and use relative or named capture group instead.
For example, if you want to search repeated characters, use
S<< C<(\w)\g{-1}> >> or S<< C<(?E<lt>cE<gt>\w)\g{c}> >> rather than
S<< C<(\w)\1> >>.
Extended Bracketed Character Classes (C<(?[...])>) and Variable Length
Lookbehind can be used without warnings. See
L<perlrecharclass/"Extended Bracketed Character Classes"> and
L<perlre/"(?<=pattern)">.
=over 7
=item B<-e> I<pattern>, B<--and>=I<pattern>
Specify the positive match pattern. Next command prints lines containing
all of C<foo>, C<bar> and C<baz>.
greple -e foo -e bar -e baz
=item B<-t> I<pattern>, B<--may>=I<pattern>
Specify the optional (tentative) match pattern. Next command prints
lines containing C<foo> and C<bar>, and highlights C<baz> if it exists.
greple -e foo -e bar -t baz
Since it does not affect the bare pattern argument, you can add the
highlighting word to the end of the command argument as follows.
greple foo file
greple foo file -t bar
greple foo file -t bar -t baz
=item B<-r> I<pattern>, B<--must>=I<pattern>
Specify the required match pattern. If one or more required pattern
exist, other positive match pattern becomes optional.
greple -r foo -r bar -e baz
Because C<-t> promotes all other C<-e> patterns to required, the next command
does the same thing. Mixing C<-r>, C<-e> and C<-t> is not recommended,
though.
greple -r foo -e bar -t baz
=item B<-v> I<pattern>, B<--not>=I<pattern>
Specify the negative match pattern. Because it does not affect the
bare pattern argument, you can narrow down the search result like
this.
greple foo file
greple foo file -v bar
greple foo file -v bar -v baz
=back
In the above pattern options, space characters are treated specially.
They are replaced by the pattern which matches any number of white
spaces including newline. So the pattern can expand to multiple
lines. Next commands search the series of word C<foo> C<bar> C<baz>
even if they are separated by newlines.
greple -e 'foo bar baz'
This is done by converting pattern C<foo bar baz> to
C<foo\s+bar\s+baz>, so that word separator can match one or more white
spaces.
As for Asian wide characters, pattern is cooked as zero or more white
spaces can be allowed between any characters. So Japanese string
pattern C<æ¥æ¬èª> will be converted to C<< æ¥\s*æ¬\s*èª >>.
If you don't want these conversion, use C<-E> (or C<--re>) option.
=over 4
=item B<-x> I<pattern>, B<--le>=I<pattern>
Treat the pattern string as a collection of tokens separated by
spaces. Each token is interpreted by the first character. Token
start with C<-> means B<negative> pattern, C<?> means B<optional>, and
C<+> does B<required>.
The next example prints lines containing C<foo> and C<yabba>,
and none of C<bar> and C<dabba>, with highlighting C<baz> and C<doo>
if they exist.
greple --le='foo -bar ?baz yabba -dabba ?doo'
This is the summary of start character for C<--le> option:
+ Required pattern
- Negative match pattern
? Optional pattern
& Function call (see next section)
=item B<-x> [B<+?->]B<&>I<function>, B<--le>=[B<+?->]B<&>I<function>
If the pattern starts with ampersand (C<&>), it is treated as a
function, and the function is called instead of searching pattern.
Function call interface is the same as the one for block/region options.
If you have a definition of I<odd_line> function in your F<.greplerc>,
which is described in this manual later, you can print odd number
lines like this:
greple -n '&odd_line' file
Required (C<+>), optional (C<?>) and negative (C<->) mark can be used
for function pattern.
B<CALLBACK FUNCTION>: Region list returned by function can have two
extra elements besides start/end position. Third element is index.
Fourth element is a callback function pointer which will be called to
produce string to be shown in command output. Callback function is
called with four arguments (start position, end position, index,
matched string) and expected to return replacement string. If the
function returns C<undef>, the result is not changed.
script/greple view on Meta::CPAN
=item B<-F>, B<--filter>
Use B<greple> as a filter. This option implicitly sets B<--all>,
B<--need>=C<0> and B<--exit>=C<0>, so the entire input is printed
regardless of whether or not any pattern is matched.
With this option, a search pattern is not required. The first
argument is treated as a filename, not a pattern. To specify a
pattern, use an explicit option such as B<-E>. When a
pattern is given, matched parts are highlighted but no lines are
excluded from the output.
Can be negated by the B<--no-filter> option.
=item B<-m> I<n>[,I<m>], B<--max-count>=I<n>[,I<m>]
Set the maximum count of blocks to be shown to I<n>.
Actually I<n> and I<m> are simply passed to perl L<splice> function as
I<offset> and I<length>. Works like this:
greple -m 10 # get first 10 blocks
greple -m 0,-10 # get last 10 blocks
greple -m 0,10 # remove first 10 blocks
greple -m -10 # remove last 10 blocks
greple -m 10,10 # remove 10 blocks from 10th (10-19)
This option does not affect search performance or command exit
status.
Note that B<grep> command also has the same option, but its behavior is
different when invoked with multiple files. B<greple> produces given
number of output for each file, while B<grep> takes it as a total
number of output.
=item B<-m> I<*>, B<--max-count>=I<*>
In fact, I<n> and I<m> can repeat as many as possible. Next example
removes first 10 blocks (by C<0,10>), then get first 10 blocks from
the result (by C<10>). Consequently, get 10 blocks from 10th (10-19).
greple -m 0,10,10
Next command gets first 20 (by C<20,>) and gets last 10 (by C<,-10>),
producing same result. Empty string behaves like absence for
I<length> and zero for I<offset>.
greple -m 20,,,-10
=item B<-A>[I<n>], B<--after-context>[=I<n>]
=item B<-B>[I<n>], B<--before-context>[=I<n>]
=item B<-C>[I<n>], B<--context>[=I<n>]
Print I<n>-blocks before/after matched string. The value I<n> can be
omitted and the default is 2. When used with C<--paragraph> or
C<--block> option, I<n> means number of paragraph or block.
Actually, these options expand the area of logical operation. It
means
greple -C1 'foo bar baz'
matches following text.
foo
bar
baz
Moreover
greple -C1 'foo baz'
also matches this text, because matching blocks around C<foo> and
C<bar> overlaps each other and makes single block.
=item B<--join>
=item B<--joinby>=I<string>
Convert newline character found in matched string to empty or specified
I<string>. Using C<--join> with C<-o> (only-matching) option, you can
collect searching sentence list in one per line form. This is
sometimes useful for Japanese text processing. For example, next
command prints the list of KATAKANA words, including those spread
across multiple lines.
greple -ho --join '\p{InKatakana}+(\n\p{InKatakana}+)*'
Space separated word sequence can be processed with C<--joinby>
option. Next example prints all C<for *something*> pattern in pod
documents within Perl script.
greple -Mperl --pod -ioe '\bfor \w+' --joinby ' '
=item B<--[no]newline>
Since B<greple> can handle arbitrary blocks other than normal text
lines, they sometimes do not end with newline character. Option C<-o>
makes similar situation. In that case, extra newline is appended at
the end of block to be shown. Option C<--no-newline> disables this
behavior.
=item B<--filestyle>=[C<line>,C<once>,C<separate>], B<--fs>
Default style is I<line>, and B<greple> prints filename at the
beginning of each line. Style I<once> prints the filename only once
at the first time. Style I<separate> prints filename in the separate
line before each line or block.
=item B<--linestyle>=[C<line>,C<separate>], B<--ls>
Default style is I<line>, and B<greple> prints line numbers at the
beginning of each line. Style I<separate> prints line number in the
separate line before each line or block.
=item B<--blockstyle>=[C<line>,C<separate>], B<--bs>
Default style is I<line>, and B<greple> prints block numbers at the
script/greple view on Meta::CPAN
Contrary to the next C<--block> option, C<--border> never produce
disjoint records.
If you want to treat entire file as a single block, setting border to
start or end of whole data is efficient way. Next commands works
same.
greple --border '\A' # beginning of file
greple --border '\z' # end of file
=item B<--block>=I<pattern>
=item B<--block>=I<&sub>
Specify the record block to display. Default block is a single line.
Empty blocks are ignored. When blocks are not continuous, the match
occurred outside blocks are ignored.
If multiple block options are given, overlapping blocks are merged
into a single block.
Please be aware that this option is sometimes quite time consuming,
because it finds all blocks before processing.
=item B<--blockend>=I<string>
Change the end mark displayed after C<-pABC> or C<--block> options.
Default value is "--". Escape sequences C<\t>, C<\n>, C<\r>, and
C<\f> are recognized.
=item B<--join-blocks>
Join consecutive blocks together. Logical operation is done for each
individual blocks, but if the results are back-to-back connected, make
them single block for final output.
=back
B<Related options:>
B<-b>/B<--block-number> (L</STYLES>),
B<-A>/B<-B>/B<-C> (L</STYLES>),
B<--inside>/B<--outside>/B<--include>/B<--exclude> (L</REGIONS>)
=head2 REGIONS
=over 7
=item B<--inside>=I<pattern>
=item B<--outside>=I<pattern>
Option C<--inside> and C<--outside> limit the text area to be matched.
For simple example, if you want to find string C<and> not in the word
C<command>, it can be done like this.
greple --outside=command and
The block can be larger and expand to multiple lines. Next command
searches from C source, excluding comment part.
greple --outside '(?s)/\*.*?\*/'
Next command searches only from POD part of the perl script.
greple --inside='(?s)^=.*?(^=cut|\Z)'
When multiple B<inside> and B<outside> regions are specified, those
regions are mixed up in union way.
In multiple color environment, and if single keyword is specified,
matches in each C<--inside>/C<--outside> region is printed in different
color. Forcing this operation with multiple keywords, use
C<--regioncolor> option.
=item B<--inside>=I<&function>
=item B<--outside>=I<&function>
If the pattern name begins by ampersand (&) character, it is treated
as a name of subroutine which returns a list of blocks. Using this
option, user can use arbitrary function to determine from what part of
the text they want to search. User defined function can be defined in
F<.greplerc> file or by module option.
=item B<--include>=I<pattern>
=item B<--exclude>=I<pattern>
=item B<--include>=I<&function>
=item B<--exclude>=I<&function>
C<--include>/C<--exclude> option behave exactly same as
C<--inside>/C<--outside> when used alone.
When used in combination, C<--include>/C<--exclude> are mixed in AND
manner, while C<--inside>/C<--outside> are in OR.
Thus, in the next example, first line prints all matches, and second
does none.
greple --inside PATTERN --outside PATTERN
greple --include PATTERN --exclude PATTERN
You can make up desired matches using C<--inside>/C<--outside> option,
then remove unnecessary part by C<--include>/C<--exclude>
=item B<--strict>
Limit the match area strictly.
By default, C<--block>, C<--inside>/C<outside>,
C<--include>/C<--exclude> option allows partial match within the
specified area. For instance,
greple --inside and command
script/greple view on Meta::CPAN
second function will get the result of the first function. The
command will print the final result of the last function.
This option and next B<--continue> are no more recommended to use
because B<--colormap> and B<--callback> functions are more simple and
powerful.
=item B<--continue>
When C<--print> option is given, B<greple> will immediately print the
result returned from print function and finish the cycle. Option
C<--continue> forces to continue normal printing process after print
function called. So please be sure that all data being consistent.
=back
For these run-time functions, optional argument list can be set in the
form of C<key> or C<key=value>, connected by comma. These arguments
will be passed to the function in key => value list. Sole key will
have the value one. Also processing file name is passed with the key
of C<FILELABEL> constant. As a result, the option in the next form:
--begin function(key1,key2=val2)
--begin function=key1,key2=val2
will be transformed into following function call:
function(&FILELABEL => "filename", key1 => 1, key2 => "val2")
As described earlier, C<FILELABEL> parameter is not given to the
function specified with module option. So
-Mmodule::function(key1,key2=val2)
-Mmodule::function=key1,key2=val2
simply becomes:
function(key1 => 1, key2 => "val2")
The function can be defined in F<.greplerc> or modules. Assign the
arguments into hash, then you can access argument list as member of
the hash. It's safe to delete FILELABEL key if you expect random
parameter is given. Content of the target file can be accessed by
C<$_>. Ampersand (C<&>) is required to avoid the hash key is
interpreted as a bare word.
sub function {
my %arg = @_;
my $filename = delete $arg{&FILELABEL};
$arg{key1}; # 1
$arg{key2}; # "val2"
$_; # contents
}
=head2 OTHERS
=over 7
=item B<--usage>[=I<expand>]
B<Greple> print usage and exit with option C<--usage>, or no valid
parameter is not specified. In this case, module option is displayed
with help information if available. If you want to see how they are
expanded, supply something not empty to C<--usage> option, like:
greple -Mmodule --usage=expand
=item B<--version>
Show version.
=item B<--exit>=I<number>
When B<greple> executed normally, it exit with status 0 or 1 depending
on something matched or not. Sometimes we want to get status 0 even
if nothing matched. This option set the status code for normal
execution. It still exits with non-zero status when error occurred.
=item B<--man>, B<--doc>
Show manual page.
Display module's manual page when used with C<-M> option.
=item B<--show>, B<--less>
Show module file contents. Use with C<-M> option.
=item B<--path>
Show module file path. Use with C<-M> option.
=item B<--norc>
Do not read startup file: F<~/.greplerc>. This option has to be
placed before any other options including C<-M> module options.
Setting C<GREPLE_NORC> environment has the same effect.
=begin comment
=item B<-d> I<flags>
Display information. Various kinds of debug, diagnostic, monitor
information can be displayed by giving appropriate flag to -d option.
c: color information
d: directory information
e: eval string
f: processing file name
m: misc debug information
n: number of processing files
o: option related information
p: run `ps' command before termination (on Unix)
s: statistic information
u: unused options
v: internal match information
=end comment
=item B<--error>=I<action>
As B<greple> tries to read data as a character string, sometimes fails
to convert them into internal representation, and the file is skipped
without processing by default. This works fine to skip binary
data. (B<skip>)
Also sometimes encounters code mapping error due to character
script/greple view on Meta::CPAN
=item B<GREPLE_NORC>
If set non-empty string, startup file F<~/.greplerc> is not processed.
=item B<DEBUG_GETOPT>
Enable L<Getopt::Long> debug option.
=item B<DEBUG_GETOPTEX>
Enable L<Getopt::EX> debug option.
=item B<NO_COLOR>
If true, all coloring capability with ANSI terminal sequence is
disabled. See L<https://no-color.org/>.
=back
Before starting execution, B<greple> reads the file named F<.greplerc>
on user's home directory. Following directives can be used.
=over 7
=item B<option> I<name> string
Argument I<name> of B<option> directive is user defined option name.
The rest are processed by C<shellwords> routine defined in
Text::ParseWords module. Be sure that this module sometimes requires
escape backslashes.
Any kind of string can be used for option name but it is not combined
with other options.
option --fromcode --outside='(?s)\/\*.*?\*\/'
option --fromcomment --inside='(?s)\/\*.*?\*\/'
If the option named B<default> is defined, it will be used as a
default option.
For the purpose to include following arguments within replaced
strings, two special notations can be used in option definition.
String C<$E<lt>nE<gt>> is replaced by the I<n>th argument after the
substituted option, where I<n> is number start from one. String
C<$E<lt>shiftE<gt>> is replaced by following command line argument and
the argument is removed from option list.
For example, when
option --line --le &line=$<shift>
is defined, command
greple --line 10,20-30,40
will be evaluated as this:
greple --le &line=10,20-30,40
=item B<expand> I<name> I<string>
Define local option I<name>. Command B<expand> is almost same as
command B<option> in terms of its function. However, option defined
by this command is expanded in, and only in, the process of
definition, while option definition is expanded when command arguments
are processed.
This is similar to string macro defined by following B<define>
command. But macro expansion is done by simple string replacement, so
you have to use B<expand> to define option composed by multiple
arguments.
=item B<define> I<name> string
Define macro. This is similar to B<option>, but argument is not
processed by I<shellwords> and treated just a simple text, so
meta-characters can be included without escape. Macro expansion is
done for option definition and other macro definition. Macro is not
evaluated in command line option. Use option directive if you want to
use in command line,
define (#kana) \p{InKatakana}
option --kanalist --nocolor -o --join --re '(#kana)+(\n(#kana)+)*'
help --kanalist List up Katakana string
=item B<help> I<name>
If B<help> directive is used for same option name, it will be printed
in usage message. If the help message is C<ignore>, corresponding
line won't show up in the usage.
=item B<builtin> I<spec> I<variable>
Define built-in option which should be processed by option parser.
Arguments are assumed to be L<Getopt::Long> style spec, and
I<variable> is string start with C<$>, C<@> or C<%>. They will be
replaced by a reference to the object which the string represent.
See B<pgp> module for example.
=item B<autoload> I<module> I<options> ...
Define module which should be loaded automatically when specified
option is found in the command arguments.
For example,
autoload -Mdig --dig --git
replaces option "C<--dig>" to "C<-Mdig --dig>", so that B<dig> module
is loaded before processing C<--dig> option.
=back
Environment variable substitution is done for string specified by
C<option> and C<define> directives. Use Perl syntax B<$ENV{NAME}> for
this purpose. You can use this to make a portable module.
When B<greple> found C<__PERL__> line in F<.greplerc> file, the rest
of the file is evaluated as a Perl program. You can define your own
subroutines which can be used by C<--inside>/C<--outside>,
C<--include>/C<--exclude>, C<--block> options.
For those subroutines, file content will be provided by global
variable C<$_>. Expected response from the subroutine is the list of
array references, which is made up by start and end offset pairs.
For example, suppose that the following function is defined in your
F<.greplerc> file. Start and end offset for each pattern match can be
taken as array element C<$-[0]> and C<$+[0]>.
__PERL__
sub odd_line {
my @list;
my $i;
while (/.*\n/g) {
push(@list, [ $-[0], $+[0] ]) if ++$i % 2;
}
@list;
}
You can use next command to search pattern included in odd number
lines.
% greple --inside '&odd_line' pattern files...
=head1 MODULE
You can expand the B<greple> command using module. Module files are
placed at F<App/Greple/> directory in Perl library, and therefor has
B<App::Greple::module> package name.
In the command line, module have to be specified preceding any other
options in the form of B<-M>I<module>. However, it also can be
specified at the beginning of option expansion.
If the package name is declared properly, C<__DATA__> section in the
module file will be interpreted same as F<.greplerc> file content. So
you can declare the module specific options there. Functions declared
in the module can be used from those options, it makes highly
expandable option/programming interaction possible.
Using C<-M> without module argument will print available module list.
Option C<--man> will display module document when used with C<-M>
option. Use C<--show> option to see the module itself. Option
C<--path> will print the path of module file.
See this sample module code. This sample defines options to search
from pod, comment and other segment in Perl script. Those capability
can be implemented both in function and macro.
package App::Greple::perl;
use Exporter 'import';
our @EXPORT = qw(pod comment podcomment);
our %EXPORT_TAGS = ( );
our @EXPORT_OK = qw();
use App::Greple::Common;
use App::Greple::Regions;
my $pod_re = qr{^=\w+(?s:.*?)(?:\Z|^=cut\s*\n)}m;
my $comment_re = qr{^(?:\h*#.*\n)+}m;
sub pod {
match_regions(pattern => $pod_re);
}
sub comment {
match_regions(pattern => $comment_re);
}
sub podcomment {
match_regions(pattern => qr/$pod_re|$comment_re/);
}
1;
__DATA__
define :comment: ^(\s*#.*\n)+
define :pod: ^=(?s:.*?)(?:\Z|^=cut\s*\n)
#option --pod --inside :pod:
#option --comment --inside :comment:
#option --code --outside :pod:|:comment:
option --pod --inside '&pod'
option --comment --inside '&comment'
option --code --outside '&podcomment'
You can use the module like this:
greple -Mperl --pod default greple
greple -Mperl --colorful --code --comment --pod default greple
If special subroutine C<initialize()> and C<finalize()> are defined in
the module, they are called at the beginning with
L<Getopt::EX::Module> object as a first argument. Second argument is
the reference to C<@ARGV>, and you can modify actual C<@ARGV> using
it. See L<App::Greple::find> module as an example.
( run in 0.307 second using v1.01-cache-2.11-cpan-b85c58fdc1d )