Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re^3: Code Works But Not Sure How (updated)

by haukex (Abbot)
on Feb 11, 2018 at 12:36 UTC ( #1208950=note: print w/replies, xml ) Need Help??


in reply to Re^2: Code Works But Not Sure How
in thread Code Works But Not Sure How

The code you showed still does not work because it suffers from the problem 1nickt and I explained: With "make_menu_items();", you're not giving it any arguments, so inside make_menu_items, $items is still undef, this is the reason you get the "Use of uninitialized value" warning. Again, use Data::Dumper or Data::Dump to actually look at the values you are working with, see the Basic debugging checklist.

but then I have to pass the array size.

While necessary in languages like C, it's not necessary in Perl because you can easily get the size of an array via scalar(@array), or the index of its last element via $#array. For an array reference like the one you're passing to new, you can get its size via scalar(@{$arrayref}), or the index of its last element via $#{$arrayref}. There are also shorter ways to express the size of an array, but the aforementioned should work in just about any situation.

Update: Plus, another central point is that Perl provides the foreach loop, where you don't even need to know the size of the array you are iterating over, and that kind of loop is almost always better. Plus, it "aliases" the iterator variable to the actual array item, so you can modify array items through it. The following prints "("Laziness is cool", "Impatience is cool", "Hubris is cool")":

use warnings; use strict; use Data::Dump; my @array = ('Laziness', 'Impatience', 'Hubris'); for my $item (@array) { $item = "$item is cool"; } dd @array;

Replies are listed 'Best First'.
Re^4: Code Works But Not Sure How (updated)
by RichHamilton (Novice) on Feb 11, 2018 at 13:31 UTC
    Thanks again I'll look over the debugging checklist. I hadn't tried the foreach loop yet, since I wasn't sure how to access it. I was look at it strictly as {$menu_items = []}.
      I wasn't sure how to access it. I was look at it strictly as {$menu_items = []}.

      Have a look at perlreftut (and for details, perlref): An array reference can always be dereferenced with @{...}, so in this case foreach my $item ( @{ $items->{menu_items} } ).

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1208950]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2018-07-21 11:59 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?















    Results (448 votes). Check out past polls.

    Notices?