📄 globmapper.pm
字号:
push @{ $self->{Pairs} }, [$inFile, $outFile]; } } return 1 ;}sub getFileMap{ my $self = shift ; return $self->{Pairs} ;}sub getHash{ my $self = shift ; return { map { $_->[0] => $_->[1] } @{ $self->{Pairs} } } ;}1;__END__=head1 NAMEFile::GlobMapper - Extend File Glob to Allow Input and Output Files=head1 SYNOPSIS use File::GlobMapper qw( globmap ); my $aref = globmap $input => $output or die $File::GlobMapper::Error ; my $gm = new File::GlobMapper $input => $output or die $File::GlobMapper::Error ;=head1 DESCRIPTIONB<WARNING Alpha Release Alert!> =over 5=item * This code is a work in progress. =item * There are known bugs. =item * The interface defined here is tentative. =item * There are portability issues. =item * Do not use in production code.=item * Consider yourself warned!=backThis module needs Perl5.005 or better.This module takes the existing C<File::Glob> module as a starting point andextends it to allow new filenames to be derived from the files matched byC<File::Glob>.This can be useful when carrying out batch operations on multiple files thathave both an input filename and output filename and the output file can bederived from the input filename. Examples of operations where this can beuseful include, file renaming, file copying and file compression.=head2 Behind The ScenesTo help explain what C<File::GlobMapper> does, consider what code youwould write if you wanted to rename all files in the current directorythat ended in C<.tar.gz> to C<.tgz>. So say these files are in thecurrent directory alpha.tar.gz beta.tar.gz gamma.tar.gzand they need renamed to this alpha.tgz beta.tgz gamma.tgzBelow is a possible implementation of a script to carry out the rename(error cases have been omitted) foreach my $old ( glob "*.tar.gz" ) { my $new = $old; $new =~ s#(.*)\.tar\.gz$#$1.tgz# ; rename $old => $new or die "Cannot rename '$old' to '$new': $!\n; }Notice that a file glob pattern C<*.tar.gz> was used to match theC<.tar.gz> files, then a fairly similar regular expression was used inthe substitute to allow the new filename to be created.Given that the file glob is just a cut-down regular expression and that ithas already done a lot of the hard work in pattern matching the filenames,wouldn't it be handy to be able to use the patterns in the fileglob todrive the new filename?Well, that's I<exactly> what C<File::GlobMapper> does. Here is same snippet of code rewritten using C<globmap> for my $pair (globmap '<*.tar.gz>' => '<#1.tgz>' ) { my ($from, $to) = @$pair; rename $from => $to or die "Cannot rename '$old' to '$new': $!\n; }So how does it work?Behind the scenes the C<globmap> function does a combination of afile glob to match existing filenames followed by a substituteto create the new filenames. Notice how both parameters to C<globmap> are strings that are delimited by <>.This is done to make them look more like file globs - it is just syntacticsugar, but it can be handy when you want the strings to be visuallydistinctive. The enclosing <> are optional, so you don't have to use them - infact the first thing globmap will do is remove these delimiters if they arepresent.The first parameter to C<globmap>, C<*.tar.gz>, is an I<Input File Glob>. Once the enclosing "< ... >" is removed, this is passed (more orless) unchanged to C<File::Glob> to carry out a file match.Next the fileglob C<*.tar.gz> is transformed behind the scenes into afull Perl regular expression, with the additional step of wrapping eachtransformed wildcard metacharacter sequence in parenthesis.In this case the input fileglob C<*.tar.gz> will be transformed intothis Perl regular expression ([^/]*)\.tar\.gzWrapping with parenthesis allows the wildcard parts of the Input FileGlob to be referenced by the second parameter to C<globmap>, C<#1.tgz>,the I<Output File Glob>. This parameter operates just like the replacementpart of a substitute command. The difference is that the C<#1> syntaxis used to reference sub-patterns matched in the input fileglob, ratherthan the C<$1> syntax that is used with perl regular expressions. Inthis case C<#1> is used to refer to the text matched by the C<*> in theInput File Glob. This makes it easier to use this module where theparameters to C<globmap> are typed at the command line.The final step involves passing each filename matched by the C<*.tar.gz>file glob through the derived Perl regular expression in turn andexpanding the output fileglob using it.The end result of all this is a list of pairs of filenames. By defaultthat is what is returned by C<globmap>. In this example the data structurereturned will look like this ( ['alpha.tar.gz' => 'alpha.tgz'], ['beta.tar.gz' => 'beta.tgz' ], ['gamma.tar.gz' => 'gamma.tgz'] )Each pair is an array reference with two elements - namely the I<from>filename, that C<File::Glob> has matched, and a I<to> filename that isderived from the I<from> filename.=head2 LimitationsC<File::GlobMapper> has been kept simple deliberately, so it isn't intended tosolve all filename mapping operations. Under the hood C<File::Glob> (or forolder versions of Perl, C<File::BSDGlob>) is used to match the files, so youwill never have the flexibility of full Perl regular expression.=head2 Input File GlobThe syntax for an Input FileGlob is identical to C<File::Glob>, exceptfor the following=over 5=item 1.No nested {}=item 2.Whitespace does not delimit fileglobs.=item 3.The use of parenthesis can be used to capture parts of the input filename.=item 4.If an Input glob matches the same file more than once, only the firstwill be used.=backThe syntax=over 5=item B<~>=item B<~user>=item B<.>Matches a literal '.'.Equivalent to the Perl regular expression \.=item B<*>Matches zero or more characters, except '/'. Equivalent to the Perlregular expression [^/]*=item B<?>Matches zero or one character, except '/'. Equivalent to the Perlregular expression [^/]?=item B<\>Backslash is used, as usual, to escape the next character.=item B<[]>Character class.=item B<{,}>Alternation=item B<()>Capturing parenthesis that work just like perl=backAny other character it taken literally.=head2 Output File GlobThe Output File Glob is a normal string, with 2 glob-like features.The first is the '*' metacharacter. This will be replaced by the completefilename matched by the input file glob. So *.c *.ZThe second is Output FileGlobs take the =over 5=item "*"The "*" character will be replaced with the complete input filename.=item #1Patterns of the form /#\d/ will be replaced with the =back=head2 Returned Data=head1 EXAMPLES=head2 A Rename scriptBelow is a simple "rename" script that uses C<globmap> to determine thesource and destination filenames. use File::GlobMapper qw(globmap) ; use File::Copy; die "rename: Usage rename 'from' 'to'\n" unless @ARGV == 2 ; my $fromGlob = shift @ARGV; my $toGlob = shift @ARGV; my $pairs = globmap($fromGlob, $toGlob) or die $File::GlobMapper::Error; for my $pair (@$pairs) { my ($from, $to) = @$pair; move $from => $to ; }Here is an example that renames all c files to cpp. $ rename '*.c' '#1.cpp'=head2 A few example globmapsBelow are a few examples of globmapsTo copy all your .c file to a backup directory '</my/home/*.c>' '</my/backup/#1.c>'If you want to compress all '</my/home/*.[ch]>' '<*.gz>'To uncompress '</my/home/*.[ch].gz>' '</my/home/#1.#2>'=head1 SEE ALSOL<File::Glob|File::Glob>=head1 AUTHORThe I<File::GlobMapper> module was written by Paul Marquess, F<pmqs@cpan.org>.=head1 COPYRIGHT AND LICENSECopyright (c) 2005 Paul Marquess. All rights reserved.This program is free software; you can redistribute it and/ormodify it under the same terms as Perl itself.
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -