There is no such thing as an "Array of variables". This
my @Variables = ( $Map_Request_Date,$Map_Due_Date,$Map_Cutover_Date,$M +ap_Complete_Date,$Map_Approved_Date);
does not do what you think it does. You are assigning the contents of those variables to a new array, not the variables themselves. In the loop you are modifying the values in the array, not the original variables:
my($foo, $bar) = (1,2); my @vars = ($foo, $bar); foreach my $var (@vars) { $var += 4; } print "\@vars: @vars\n"; print "\$foo: $foo\n"; print "\$bar: $bar\n"; __END__ @vars: 5 6 $foo: 1 $bar: 2
Is that what you want to do? Or do you want to modify the values in the variables? In that case, you have two possibilities:
The loop variable $var is an alias for each item in the list. The same happens if you iterate over an array: the loop variable is then an alias to each slot in the array.my($foo, $bar) = (1,2); foreach my $var ($foo, $bar) { $var += 4; } print "\$foo: $foo\n"; print "\$bar: $bar\n"; __END__ $foo: 5 $bar: 6
In this case, the @vars array is populated with references to the original variables, which are values. To modify what they point at, they must be de-referenced. Doing so gives access to the body of the variable of which the reference has been taken.my($foo, $bar) = (1,2); my @vars = \($foo, $bar); # note the backslash before the list # this would do the same: my @vars = (\$foo, \$bar); foreach my $var (@vars) { $$var += 4; # note the de-referencing $ before $var } print "\@vars: @vars\n"; print "\$foo: $foo\n"; print "\$bar: $bar\n"; __END__ @vars: SCALAR(0x15ae7a0) SCALAR(0x15ae830) $foo: 5 $bar: 6
Almost always the first way is used.
Then, your %Months hash only holds constants, but you are setting it up and tearing it down everytime through the loop. Move that outside the loop. You can limit the scope of that hash by wrapping all into a bare block:
{ my %Months = (...); ... foreach $var (...) { ... } } # %Months not defined here anymore
Lastly, it is easier to reformat your date strings using split and sprintf:
my %Months = (Dec => 12); my $date = 'Dec 1 2016 18:15'; my @pcs = split " ", $date; $date = sprintf "%02d %02d %d %s",$Months{$pcs[0]}, @pcs[1..3]; print "date: '$date'\n"; __END__ date: '12 01 2016 18:15'
The construct @pcs[1..3] is an array slice of @pcs from index 1 to 3.
update: add/fix links
In reply to Re: Array of variables
by shmem
in thread Array of variables
by Michael W
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |