By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,834 Members | 2,240 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,834 IT Pros & Developers. It's quick & easy.

Populate array with split problem.

Expert 100+
P: 176
Hello all. I have a problem which seems to make no sense to me.
Therefore I must be doing something wrong.

I am trying to populate an array using split with a regexe.
Here is the code (snippet only).
Expand|Select|Wrap|Line Numbers
  1. my $date = $q->param('date'); # 20090112 format
  2. @dateArray = split(/(\d{4})(\d{2})(\d{2})/, $date);
After this I loop through the array using print and all the values show up.
BUT if I try to access a particular indice nothing shows up. ???

Expand|Select|Wrap|Line Numbers
  2. # After above code
  3. for(@dateArray){
  4. print $_, "\n";
  5. }
  7. # This works printing 2009 \n 01 \n 12 \n
  8. # BUT....
  10. print $dateArray[0]; # OR...
  11. print "$dateArray[0]";
  13. # Prints nothing to the screen.
What am I doing wrong?

I really need the three individual values, NOT the whole array.
Is there a better what to accomplish this without split?

I just need to pass a number, and be able to use the parts separately.

thanks in advance!
Apr 10 '09 #1
Share this Question
Share on Google+
5 Replies

Expert 2.5K+
P: 4,059
Try this:

Expand|Select|Wrap|Line Numbers
  1. for my $i (0..$#dateArray) {
  2.    print "index $i = <$dateArray[$i]>\n";
  3. }
See what gets printed. The <> brackets are so you can see if there are empty elements in the array. Keep in mind you have used capturing parentheses in the regexp so the split delimiter is also being saved in the array.
Apr 10 '09 #2

Expert 100+
P: 176
Very interesting.
Here is the results from your code KevinADC.
Expand|Select|Wrap|Line Numbers
  1. index 0 = <>
  2. index 1 = <2009>
  3. index 2 = <01>
  4. index 3 = <12>
My only guess is the capturing vars, $1, $2, etc..were used as indices?


PS- I almost didn't notice your new avatar. Nice.
Apr 10 '09 #3

Expert 2.5K+
P: 4,059
No, the capturing vars are not used as the array indexes. I think the problem is you are using split() when you should not be. Just use a matching regexp:

Expand|Select|Wrap|Line Numbers
  1. @dateArray = $date =~ m/(\d{4})(\d{2})(\d{2})/;
if there is more than one set of dates to capture add the "g" modifier to the end of the regexp,
Apr 10 '09 #4

Expert 100+
P: 176
Ah ha! That's it.
That works just as I expect it to.

In fact that is exactly what I was trying to do, I had seen it before in a book and remembered it incorrectly.

Apr 10 '09 #5

Expert 2.5K+
P: 4,059
You're welcome, good to see you around here.
Apr 10 '09 #6

Post your reply

Sign in to post your reply or Sign up for a free account.