开发者

Perl assignment with a dummy placeholder

开发者 https://www.devze.com 2023-03-03 05:38 出处:网络
In other开发者_如何学C 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 in Perl:

In other开发者_如何学C 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 in Perl:

   (_,$id) = split('=',$fields[1]);

But I get the following error:

Can't modify constant item in list assignment at ./generate_datasets.pl line 17, near ");"

Execution of ./generate_datasets.pl aborted due to compilation errors.

Does Perl have a similar such pattern that I could use instead of creating a useless temporary variables?


undef serves the same purpose in Perl.

(undef, $something, $otherthing) = split(' ', $str);


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


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];


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号