为什么列表我的Perl地图只返回1? [英] Why is the list my Perl map returns just 1's?

查看:101
本文介绍了为什么列表我的Perl地图只返回1?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的代码如下:

#!/usr/bin/perl 

my @input = ( "a.txt" , "b.txt" , "c.txt" ) ;
my @output = map { $_ =~ s/\..*$// } @input ;

print @output ;

我的目的是让没有扩展名的文件名存储在数组 @output
,而是存储 s /// 返回的值,而不是在 @output ,所以结果看起来像

My intention is to let the file name without the extension stored in the array @output. but instead it stores the value returned by s/// rather than the changed file name in @output, so the result looks like

1
1
1

所以在这种情况下使用 map 的正确方法是什么? >

so what is the correct way to use map under this situation?

推荐答案

好的,首先,你可能意味着要有 $ _ =〜s / \ .. * $ // - 注意您的示例中缺少的 s 。此外,您可能意味着地图不是 grep

Ok, first off, you probably meant to have $_ =~ s/\..*$// — note the missing s in your example. Also, you probably mean map not grep.

其次,这不是你想要的。这实际上修改了 @input !在 grep (和地图和其他几个地方), $ _ 实际上是每个值的别名。所以你实际上是在改变这个价值。

Second, that doesn't do what you want. That actually modifies @input! Inside grep (and map, and several other places), $_ is actually aliased to each value. So you're actually changing the value.

另请注意,模式匹配不返回匹配的值;它返回true(如果有匹配)或false(如果没有)。这就是你所看到的1。

Also note that pattern match does not return the matched value; it returns true (if there is a match) or false (if there isn't). That's all the 1's you're seeing.

相反,请执行以下操作:

Instead, do something like this:

my @output = map {
    (my $foo = $_) =~ s/\..*$//;
    $foo;
} @input ;

第一个副本 $ _ $ foo ,然后修改 $ foo 。然后,它返回修改的值(存储在 $ foo )。您不能使用 return $ foo ,因为它是一个块,而不是子例程。

The first copies $_ to $foo, and then modifies $foo. Then, it returns the modified value (stored in $foo). You can't use return $foo, because its a block, not a subroutine.

这篇关于为什么列表我的Perl地图只返回1?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆