perlquestion
RichHamilton
<p>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:</p>
<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;
</code>
<p> So basically, the class is initialized with an array reference like this: </p>
<code>
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);
</code>
<p>So the output of data dumper looks like:</p>
<code>
$VAR1 = bless( {
'menu_items' => [
'1',
'Option 1',
'2',
'Option 2',
'3',
'Option 3',
'4',
'Option 4'
]
}, 'MyClass' );
</code>
<p>What I thought I was doing was getting the size of the of the array that is the value of <code>menuitems</code> and then loop through the array. But <code> $items = $#{$self->{menu_items}}</code> 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 <code>menuitems</code>.</p>
<p>I know I could have done defined the array using something like <code>@array=qq('1' 'Option 1' '2' 'Option 2' '3' 'Option 3' '4' 'Option 4');</code> and that have worked fine. But I thought I could just loop through <code>menuitems</code> and just use the array as coded.</p>
<p>I'd appreciate any guidance on the code any more experienced Monks can provide. Thanks in advance for your guidance.</p>