[英]How do I tell perl to execute a piece of generated Perl code?
我試圖捕獲字符串cd /a/b/c
並進行以下轉換(作為較大的Perl程序的一部分)。
如果cd /a/b/c
存在,則轉換cd /a/b/c
→ chdir '/a/b/c'
並執行chdir '/a/b/c'
我可以進行轉換; 我無法告訴perl
執行我的命令。
#!/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
輸出:
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.
您真正想要的是調度表。 遇到cd
類的命令時,您將在分派表中查找關聯的子例程,在該子例程中,將有效命令映射到要運行的代碼:
%dispatch = ( cd => sub { chdir( $_[0] ) }, ... ); while( <> ) { my( $command, @args ) = split; if( exists $dispatch{ $command } ) { $dispatch{ $command }->(@args); } }
在Mastering Perl中,我有幾個擴展的例子。 這樣做的好處是,當您有新命令時,您不會更改處理循環,而只會處理您打算處理的命令。 此外,您可以直接從配置中構造該調度表。
如果您要查找的目錄是事先已知的。
$str = "blah blah cd /a/b/c blah";
if ( $str =~ /cd \/a\/b\/c/ ){
print "found\n";
chdir("/a/b/c");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.