简体   繁体   中英

Declaring a Perl array and assigning it values by an array-slice

I was trying to split a string and rearrange the results, all in a single statement:

my $date_str = '15/5/2015';
my @directly_assigned_date_array[2,1,0] = split ('/', $date_str);

This resulted in:

syntax error at Array_slice_test.pl line 16, near "@directly_assigned_date_array["

Why is that an error?

The following works well though:

my @date_array;
@date_array[2,1,0] = split ('/', $date_str);

@vol7ron offered a different way to do it:

my @rvalue_array = (split '/', $date_str)[2,1,0];

And it indeed does the job, but it looks unintuitive, to me at least.

当您只是反转分割数组时,您可以使用以下单个语句完成相同操作: @date_array = reverse(split('/',$date_str));

Others here know much more about Perl internals than myself, but I assume it cannot perform the operation because an array slice is referencing an element of an array, which does not yet exist. Because the array has not yet been declared, it wouldn't know what address to reference.

my @array = ( split '/', $date_str )[2,1,0];

This works because split returns values in list context. Lists and arrays are very similar in Perl. You could think of an array as a super list, with extra abilities. However you choose to think of it, you can perform a list slice just like an array slice.

In the above code, you're taking the list, then reordering it using the slice and then assigning that to array. It may feel different to think about at first, but it shouldn't be too hard. Generally, you want your data operations (modifications and ordering) to be performed on the rhs of the assignment and your lhs to be the receiving end.

Keep in mind that I've also dropped some parentheses and used Perl's smart order of operation interpreting to reduce the syntax. The same code might otherwise look like the following (same operations, just more fluff):

my @array = ( split( '/', $date_str ) )[2,1,0];

As @luminos mentioned, since you only have 3 elements you're manually reversing it, you could use a reverse function; again we can make use of Perl's magic order of operation and drop the parentheses here:

my @array = reverse split '/', $date_str;

But in this case it might be too magical, so depending on your coding practice guidelines, you may want to include a set of parentheses for the split or reverse, if it increases readability and comprehension.

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