Reputation: 65
I am trying to create a manageable code in perl. I want to have a setup like this so that my last value in the array of possibly many information can have the last value assigned to $d. I still want to be able to make room for a possibility in the extension of my array at a future time
($a,$b,$c,@rest,$d) = (1,2,3,5,1,4,5,6,8,5,2,.....4,7)
I want $d to be equal to the last value(7). However, I still want a situation where I will be able to add at a future time a variable $e that will hold the new last value again. as follows
($a,$b,$c,@rest,$d,$e) = (1,2,3,5,1,4,5,6,8,5,2,.....4,7,8)
and then $d still stays as 7 and $e will become 8. I know using the variable @rest will take up all the rest of the values in my array. I'm just looking for an easy way out of extract my needed variables that are appended at the end of my array. Thanks
Upvotes: 1
Views: 208
Reputation: 66883
Or you can use an array reference ($ra
below) for an anonymous array ([...]
) instead
use warnings;
use strict;
use feature 'say';
my ($v1, $v2, $ra, $e) = (2, 4, [10..12], 5);
say for ($v1, $v2);
say "@$ra";
say $e;
Then you can tack on other variables as you wish.
This of course requires that you can separate a part of your input into an anonymous array.
If you can't do that another manageable option is to assign values to an array variable first, which you can then more easily use via indexing/slicing (@ary[0,1,2..4]
etc), and/or with pop
.
It appears that the "first" part of your input, ending with the array, won't change. Then extract that so to leave only the data that may grow in the future
my @data = (1..8, 25, 37);
my $fixed_length = 5; # number of points to always go into array
my ($v1, $v2, $v3, @ary) = splice @data, 0, 3+$fixed_length;
# (25 and 37 remain) The section above needs no changes in future
while (my $datum = shift @data) {
# deal with data that grows in time
}
This minimizes code changes, to only the processing of future data.
If the first part changes then there won't be a nice solution; you may want to reconsider the design.
Note that assigning new data to individual variables isn't a very manageable approach to start with.
Upvotes: 1
Reputation: 241848
You can populate @rest first, then use pop to extract the values from its end. Do so in the reverse order:
#!/usr/bin/perl
use warnings;
use strict;
use feature qw{ say };
my ($A, $B, $c, @rest) = (1, 2, 3, 5, 1, 4, 5, 6, 8, 5, 2, 4, 7);
my $e = pop @rest;
my $d = pop @rest;
say "@rest | $d $e";
Or, use splice, but you have to count the variables manually:
my ($d, $e) = splice @rest, -2;
Upvotes: 3