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

Why is this in Perl:

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

is rated as "cd"?

And this:

 substr('abcd',0,2); 

is rated as "ab"?

+6
source share
3 answers

Documented substr statement syntax

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

not

 substr EXPR,ARRAY 

or more general

 substr EXPR,LIST 

This is reflected in the prototype output (although you cannot always rely on it).

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

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

You can achieve what you want by 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) 
+12
source

substr has a prototype as a built-in function, so @x does not expand, it is calculated in a scalar context that returns 2, so basically you call substr ('abcd', scalar (@x))

+5
source

The first uses @x in a scalar context ... which means the size of @x , so substr('abcd',2) gives cd .

+4
source

Source: https://habr.com/ru/post/906976/


All Articles