Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

slice

perl

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.

like image 592
MeirG Avatar asked Apr 14 '26 09:04

MeirG


1 Answers

As you are just reversing the splitted array you can accomplish the same using this single statement: @date_array = reverse(split('/',$date_str));

like image 112
Luminos Avatar answered Apr 17 '26 11:04

Luminos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!