Perl assignment with a dummy placeholder

后端 未结 4 2244
北恋
北恋 2020-12-18 17:51

In other languages I\'ve used like Erlang and Python, if I am splitting a string and don\'t care about one of the fields, I can use an underscore placeholder. I tried this

相关标签:
4条回答
  • 2020-12-18 18:27

    And just to explain why you get the particular error that you see...

    _ is a internal Perl variable that can be used in the stat command to indicate "the same file as we used in the previous stat call". That way Perl uses a cached stat data structure and doesn't make another stat call.

    if (-x $file and -r _) { ... }
    

    This filehandle is a constant value and can't be written to. The variable is stored in the same typeglob as $_ and @_.

    See perldoc stat.

    0 讨论(0)
  • 2020-12-18 18:36

    You can assign to (undef).

    (undef, my $id) = split(/=/, $fields[1]);
    

    You can even use my (undef).

    my (undef, $id) = split(/=/, $fields[1]);
    

    You could also use a list slice.

    my $id = ( split(/=/, $fields[1]) )[1];
    
    0 讨论(0)
  • 2020-12-18 18:39

    You don't even need placeholders if you use Slices:

    use warnings;
    use strict;
    
    my ($id) = (split /=/, 'foo=id123')[1];
    print "$id\n";
    
    __END__
    
    id123
    
    0 讨论(0)
  • 2020-12-18 18:48

    undef serves the same purpose in Perl.

    (undef, $something, $otherthing) = split(' ', $str);
    
    0 讨论(0)
提交回复
热议问题