It's unclear what you really want. I mean, if you just have
this number, and all you need is 12, 34 and 45, you could
do:
my ($var1, $var2, $var3) = (12, 34, 45);
But what do you want to do in the general case? Always end
up with three numbers? Always get a list of 2 digit numbers?
In the former case, I'd use substr:
my $str = 123445;
my $l = int (length ($str) / 3);
my $var1 = substr $str, 0, $l;
my $var2 = substr $str, $l, $l;
my $var3 = substr $str, 2 * $l;
In the latter case, a regex will do:
my @vars = $str =~ /..?/g;
Next time, be more precise in what you want. And having a working
example helps too (123345 isn't "12" . "34" . "45").
Abigail
| [reply] [d/l] [select] |
| [reply] |
A nice simple match will cover it:
my ($var1, $var2, $var3) = $numberstring =~ /(\d{2})/g;
--
Steve Marvell
| [reply] [d/l] |
Although Abigail has provided a better answer, if you really wanted to use split you could:
my @vars = grep length, split /(..?)/, $str;
-Blake
| [reply] [d/l] |
That's awesome Blake, like your solution :)
But what "grep length" does in here?
the following:
my @vars = split /(..?)/, $str ;
return:
12 34 56
^ there is one space here, why?
and grep length get rid of the space, how that magic works?
-perlkid
| [reply] |
If the PATTERN contains parentheses, additional array elements are cre
+ated from each matching substring in the delimiter.
split(/([,-])/, "1-10,20", 3);
produces the list value
(1, '-', 10, ',', 20)
In my example, the delimiters are the parts we want to keep, the stuff between the delimiters is empty and needs to be thrown away.
Without the grep, the list you're getting back is actually
('', 12, '', 34, '', 56, '')
Where 12,34,56 are the delimiters matched by the regex and the empty strings are the "data" between the delimiters.
Obviously those empty strings have got to go, so we get rid of them by grepping out things that have no length.
-Blake
| [reply] [d/l] [select] |
If this is input by the user and you will not know how many numbers will be coming in...
You can grab the length of the input...
half it...
do a loop using the value...
then just grab substrings by an increment of twos.
Of course you will need to make sure the number coming in is even then handle other conditions on the odds.
Hope this helps.
Daniel | [reply] |