Implicit conversion to perl

I'm new to Perl, can anyone explain the following scripts to me:

#!/usr/bin/env perl
use strict;
use warnings;
sub f1($) { my ($v) = @_; print "f1 $v\n"; }
sub f2(@) { my ($v) = @_; print "f2 $v\n"; }
my $s = "ww";
my @a = ("xx", "yy", "zz");
f1 $s; f1 @a; f2 $s; f2 @a;

The output on my computer is:

f1 ww
f1 3
f2 ww
f2 xx     # why!!

Can anyone explain why the fourth result is xx? I thought it should be zz, since when the array is converted to a scalar, it should be the last element of the array.

+5
source share
3 answers

No, with an expression like:

my ($v, $foo, $bar) = @_;

$vthe first value in the array will be assigned @_, the $foosecond, etc. This is because parentheses impose a list context. Any redundant values ​​will be ignored unless one of your variables is an array, in which case it will overlap all other values.

my ($v, @foo, $bar) = @_;   # wrong! $bar will never get any value

$v , @foo . $bar undefined.

, , :

my $v = qw(a b c);

:

Useless use of a constant (a) in void context at -e line 1.
Useless use of a constant (b) in void context at -e line 1.

, LHS, , ( ) :

'a';
'b';
my $v = 'c';

, , $v , :

my ($v) = qw(a b c);  # $v is now 'a'

ETA: :

f1 , , . f1 3 (). , , ( ).

: , . , sort { code here } push @array, $foo.

, , :

sub f1 {
...
}

+4

Perl- , :
:

my $a = @tab; # get the array length
Array context:
my @newTab = @tab; # newTab is a copy of tab
Which can be reworded like this:
# 3 scalars in an array context (see parens) gets the contents of the tab
my ($a,$b,$c) = @tab; 
Here, since @tab can be wider than the number of scalars, these scalars are populated from the beginning of the tab (and not from the end). So your code:
my ($a) = @tab;
will echo the first element of the tab
+1
  • . .

  • , , . f1, .

    $ perl -E'my @a = qw( xx yy zz ); say @a; say scalar(@a);'
    xxyyzz
    3
    
  • . .

    f(@a);
    

    f($a[0], $a[1], $a[2]);
    

    RHS assignment list in evaluated context list.

    my ($v) = @_;
    

    coincides with

    my ($v) = ($_[0], $_[1], $_[2]);
    

    which coincides with

    my ($v, undef, undef) = ($_[0], $_[1], $_[2]);
    
0
source

All Articles