简体   繁体   中英

Perl substr(STRING, @ARRAY) ne substr(STRING, OFFSET, LENGTH)?

Why is this in Perl:

@x=(0,2); 
substr('abcd',@x)

evaluated as "cd"?

And this:

substr('abcd',0,2);

evaluated as "ab"?

The documented syntax of the substr operator is

substr EXPR,OFFSET,LENGTH,REPLACEMENT
substr EXPR,OFFSET,LENGTH
substr EXPR,OFFSET

not

substr EXPR,ARRAY

or the more generic

substr EXPR,LIST

This is reflected in the output of prototype (although you can't always rely on this).

$ perl -E'say prototype "CORE::substr"'
$$;$$
  • substr 's 1st argument is evaluated in scalar context.
  • substr 's 2nd argument is evaluated in scalar context.
  • substr 's 3rd argument (optional) is evaluated in scalar context.
  • substr 's 4th argument (optional) is evaluated in scalar context.

@x in scalar context is the number of elements it contains ( 2 in this case).

You can achieve what you want using the following:

sub mysubstr {
    if    (@_ == 2) { substr($_[0], $_[1]) }
    elsif (@_ == 3) { substr($_[0], $_[1], $_[2]) }
    elsif (@_ == 4) { substr($_[0], $_[1], $_[2], $_[3]) }
    else { die }
}

my @x = (0, 2);
mysubstr('abcd',@x)

substr有一个原型作为内置函数,所以@x未展开是在标量上下文中计算的,它返回2,所以基本上你调用substr('abcd',scalar(@x))

第一个在标量上下文中使用@x ...意味着@x的大小因此substr('abcd',2)给出了cd

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM