If you want to take a slice of the array, you must put a list of numbers inside the brackets [ .. ]
, not a string. One string is a list of one, of course, and it will get treated as a number and therefore converted to a number, but as you noted, it will only be the first number.
If you had use warnings
turned on, which I strongly suspect you do not, you would get the error:
Argument "3,4\n" isn't numeric in array slice at yourscript.pl ...
But Perl does convert this string to a number as best it can, and comes up with 3
.
So, that's what you did wrong. What you could do instead:
my @nums = $temp =~ /\d+/g;
my @weekdays = @shortdays[@nums];
Which would extract the integers from the string in a reasonably simple manner. It would also remove the requirement of using a specific delimiter such as comma. Note that capturing parentheses are implied when using the global /g
modifier.
If you're absolutely set on using commas, use split to extract the numbers. But be aware that this may leave whitespace and other unwanted characters.
my @nums = split /,/, $temp;
While debugging, using a statement such as
print @weekdays;
Is a bit confusing. I would recommend that you instead do this:
use Data::Dumper;
...
print Dumper \@weekdays;
Then you will see exactly what the array contains.
And of course, add these two lines to all your scripts:
use strict;
use warnings;
If you had used these, you would not be having this problem. The information and control and reduced debugging time that these two pragmas provide more than make up for the short learning curve associated with using them.