How do I tell perl to execute a piece of generated Perl code?
I am trying to catch the string cd /a/b/c
and do the following conversion
(as par开发者_运维技巧t of a larger Perl program).
If cd /a/b/c
exists then convert cd /a/b/c
→ chdir '/a/b/c'
and execute chdir '/a/b/c'
I can do the conversion; I can't tell perl
to execute my command.
#!/usr/bin/perl
use strict; use warnings;
while ( my $line = <DATA> ) {
if ( my ($path) = $line =~ m{^cd \s+ (/? (\w+) (?:/\w+)* )}x ) {
warn "Path is $path\n";
chdir $path
or warn "Cannot chdir to '$path': $!";
}
}
__DATA__
cd a
cd /a/b/c
cd /a
Output:
Path is a Cannot chdir to 'a': No such file or directory at C:\Temp\k.pl line 8, line 1. Path is /a/b/c Cannot chdir to '/a/b/c': No such file or directory at C:\Temp\k.pl line 8, line 2. Path is /a Cannot chdir to '/a': No such file or directory at C:\Temp\k.pl line 8, line 3.
What you really want is a dispatch table. When you encounter a command, like cd
, you look up an associated subroutine in the dispatch table where you map valid commands to the code that you want to run:
%dispatch = ( cd => sub { chdir( $_[0] ) }, ... ); while( <> ) { my( $command, @args ) = split; if( exists $dispatch{ $command } ) { $dispatch{ $command }->(@args); } }
I have several extended examples of this sort of thing in Mastering Perl. The nice bit about this is that you don't change the processing loop when you have new commands, and you only handle the commands you intend to handle. Furthermore, you can construct that dispatch table directly from configuration.
if the directory you want to find is known beforehand.
$str = "blah blah cd /a/b/c blah";
if ( $str =~ /cd \/a\/b\/c/ ){
print "found\n";
chdir("/a/b/c");
}
精彩评论