gpt4 book ai didi

perl - 使用 map 函数的语法错误

转载 作者:行者123 更新时间:2023-12-03 08:00:26 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Syntax error when map() returns LIST

(2 个回答)


6年前关闭。




我在使用 map 的 Perl 程序中遇到了奇怪的语法错误。功能。我有一个简单的解决方法(添加看似不必要的括号),所以这并不重要,但我不知道为什么 Perl 会在原始代码上报告语法错误,或者为什么添加括号会修复它。

我想创建一个将一系列短字符串映射到值 1 的哈希,每个短字符串都以“-”开头。 (基本上是一个集合数据结构)。我的第一次尝试与此类似:

my %hash = map { "-$_"  => 1 } qw(foo bar);

我认为这应该相当于:
my %hash = ( "-foo" => 1, "-bar" => 1 );

Perl 报告了一个语法错误。如果我替换 "-$_"通过任何单引号或双引号字符串文字,我都会收到语法错误。如果我替换 "-$_"通过 ("-$_") ,语法错误消失,代码正常工作。

我在 Perl 5.10.1、5.16.2 和 5.20.0 中得到了类似的结果。

这是一个显示问题的独立脚本(我删除了 - 前缀,因为它似乎不相关):
#!/usr/bin/perl

use strict;
use warnings;

my %h0 = map { $_ => 1 } qw(foo bar); # ok
my %h1 = map { ("$_") => 1 } qw(foo bar); # ok
my %h2 = map { "$_" => 1 } qw(foo bar); # line 8, syntax error
my %h3 = map { 'FOO' => 1 } qw(foo bar); # line 9, syntax error
my %h4 = map { "FOO" => 1 } qw(foo bar); # line 10, syntax error

以及当我尝试使用 Perl 5.20.0 运行它时的输出:

syntax error at map-bug line 8, near "} qw(foo bar)"
syntax error at map-bug line 9, near "} qw(foo bar)"
syntax error at map-bug line 10, near "} qw(foo bar)"
Execution of map-bug aborted due to compilation errors.

(对于 Perl 5.10.1 和 5.16.2,它还在第 8 行提示“没有足够的参数用于 map”。)

我已经确认,当其他两行被注释掉时,三个语法错误中的每一个仍然单独发生,因此第 9 行和第 10 行不是第 8 行的级联错误。

这是 Perl 中的一个错误,还是我错过了 Perl 语法的一些微妙之处,或者其他什么?

最佳答案

perldoc -f map :

{ starts both hash references and blocks, so map { ... could be either the start of map BLOCK LIST or map EXPR, LIST. Because Perl doesn't look ahead for the closing } it has to take a guess at which it's dealing with based on what it finds just after the {. Usually it gets it right, but if it doesn't it won't realize something is wrong until it gets to the } and encounters the missing (or unexpected) comma. The syntax error will be reported close to the }, but you'll need to change something near the { such as using a unary + or semicolon to give Perl some help:

    %hash = map {  "\L$_" => 1  } @array # perl guesses EXPR. wrong
%hash = map { +"\L$_" => 1 } @array # perl guesses BLOCK. right
%hash = map {; "\L$_" => 1 } @array # this also works
%hash = map { ("\L$_" => 1) } @array # as does this
%hash = map { lc($_) => 1 } @array # and this.
%hash = map +( lc($_) => 1 ), @array # this is EXPR and works!

%hash = map ( lc($_), 1 ), @array # evaluates to (1, @array)

or to force an anon hash constructor use +{:

    @hashes = map +{ lc($_) => 1 }, @array # EXPR, so needs
# comma at end

to get a list of anonymous hashes each with only one entry apiece.

关于perl - 使用 map 函数的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31712713/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com