http://www.perlmonks.org?node_id=1208937
RichHamilton has asked for the wisdom of the Perl Monks concerning the following question:

I could use some guidance on some code that appears to work, but I'm not sure exactly how it works. I know I need to read of on references and some on arrays for starters. What the code is supposed to do is take an array and just add single quotes around each element. I can print out the data via Data::Dumper and it appears to be fine. However, I'm not exactly sure how I got the make_menu_items subroutine to work. So here's the code:

package MyClass; use strict; use warnings; sub new { my $class = shift; my $self = { menu_items => shift, }; make_menu_items(); bless $self,$class; return $self; } sub make_menu_items { my $self = shift; my $items = $#{$self->{menu_items}}; for (my $item = 0; $item < $items; $item++) { $self->{menu_items}[$item]="'$self->{menu_items}[$item]'"; } } 1;

So basically, the class is initialized with an array reference like this:

use MyClass; use strict; use warnings; my @array = ("1","Option 1","2","Option 2","3","Option 3","4","Option +4"); my $obj = MyClass->new(\@array);

So the output of data dumper looks like:

$VAR1 = bless( { 'menu_items' => [ '1', 'Option 1', '2', 'Option 2', '3', 'Option 3', '4', 'Option 4' ] }, 'MyClass' );

What I thought I was doing was getting the size of the of the array that is the value of menuitems and then loop through the array. But  $items = $#{$self->{menu_items}} returns a -1. I had thought this would have returned the number of elements in the array. I have no clue how it (or if it even) looped through the array that is the value of menuitems.

I know I could have done defined the array using something like @array=qq('1' 'Option 1' '2' 'Option 2' '3' 'Option 3' '4' 'Option 4'); and that have worked fine. But I thought I could just loop through menuitems and just use the array as coded.

I'd appreciate any guidance on the code any more experienced Monks can provide. Thanks in advance for your guidance.