Che*_*eso 1 regex variables perl shift
这段代码有效 - 它需要一个完整的txt文件路径数组并将它们剥离,以便在$exam_nums[$x]调用时返回文件名
for (0..$#exam_nums)
{
$exam_nums[$_] =~ s/\.txt$//; #remove extension
$exam_nums[$_] =~ s/$dir//g; #remove path
}
Run Code Online (Sandbox Code Playgroud)
当我尝试为单个变量执行此操作时,它不起作用.我正在调用一个子程序并向它发送一个礼物,但该变量在结尾处是空的.(它进入if语句块,因为其中的其他行运行正常.)这是代码:
打电话到子:
notify($_);
Run Code Online (Sandbox Code Playgroud)
该$_是一个foreach(@files)循环,它的工作原理
子:
sub notify
{
if(shift)
{
$ex_num = shift;
$ex_num =~ s/\.txt$//; #remove extension
$ex_num =~ s/$dir//g; #remove path
print $ex_num;
print "\nanything";
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试取出$正则表达式的"删除扩展"部分,但这没有帮助.
Jim*_*son 13
你正在转移TWICE.if语句中的第一个移位删除了值,第二个移位什么都没有. shift有实际修改的副作用@_.除了返回第一个元素外,它还会永久删除第一个元素@_.
编辑:来自 man perlfunc
shift ARRAY
shift Shifts the first value of the array off and returns it,
shortening the array by 1 and moving everything down. If there
are no elements in the array, returns the undefined value. If
ARRAY is omitted, shifts the @_ array within the lexical scope
of subroutines and formats, ...
您试图ex_num从@_(参数列表)两次提取您的参数:( shift改变@_)与$_[0](它只是查看第一个元素@_但不改变它)不同.见perldoc -f shift.
此外,您的功能正在结束$dir,这可能是您的意图,也可能不是.(有关闭包的更多信息,请参阅perldoc perlfaq7.)我已经把它拿出来并将其作为附加函数参数添加:
sub notify
{
my ($ex_num, $dir) = @_;
return unless $ex_num;
$ex_num =~ s/\.txt$//; # remove extension
$ex_num =~ s/$dir//g; # remove path
print $ex_num . "\n";
}
Run Code Online (Sandbox Code Playgroud)