Your two biggest problems are:
- fubar()'s argument passing is really messed up. fubar() expects a plain hash, but you pass it a ref to a ref to a hash. One side or the other needs to be fixed. (Data::Dumper could have shown you this in two seconds.)
- Your foreach loop does the same thing in both passes. You need to assign the array elements to a temporary variable, and then use that variable in the loop. The default temporary variable is $_, but you can make it whatever you want using "foreach $temp (LIST) BLOCK".
Some other comments, in no particular order:
- foobar() alters global variables; This is confusing and difficult to maintain. Better to pass in the variables you want changed or create them inside the function.
- foobar() and fubar() are terrible, undescriptive names for subroutines. Just name them after what they do. foobar() could be init_items(), while fubar() could be print_items().
- Same goes for @array; Unfortunately I can't tell what it holds from your code, so I would call it @items (which is barely an improvement).
- Forget prototypes exist until Perl 6 comes out.
- print() is better than printf() 99.9% of the time. It's easier to read and you don't have to worry about casting.
You need to read perldoc perlreftut, but also perldoc perlsub (argument passing conventions) and perldoc perlsyn (foreach syntax).
Here is the fixed code. Notice how you can tell what the subroutines will do -- by their names -- before you even read them.
#!/bin/perl
use strict;
use warnings;
my @items = init_items();
print "Printing the array ...\n";
foreach my $item (@items) {
print_items($item);
}
######################
sub init_items {
return (
{
id => 1,
status => 0,
loc => 'awx1',
},
{
id => 2,
status => 1,
loc => 'xxx1',
},
);
}
sub print_items {
my $item = shift;
print "Thread <$item->{id}>, status <$item->{status}>, location <$
+item->{loc}>\n";
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.