Beginner's list/return/glob problem

L

Lars Eighner

This works fine to produce a list of partial file names when
there are matching files:

(main)

if ( gen::listdbs() )
{
$content .= $main::cur->start_ul;
foreach my $item (gen::listdbs()) { $content .= $main::cur->li($item);}
$content .= $main::cur->end_ul;
}
else
{ $content .= $main::cur->p("No databases found"); }


(gen)

sub listdbs {
my @list = undef;
my $i=0;
while (<$tun::datadir/*$tun::dbsuf>)
{
$_ =~ s#$tun::datadir/(.*)$tun::dbsuf#$1#;
$list[$i] = $_;
$i++;
}
return @list;
}

Once again, it works fine when there are values, but fails when
I think @list should still be undefined. (All testing with -w
and strict - no exceptions.)

When there are no matching files, the result is a one-item
list with empty contents.

I suspect

if ( gen::listdbs() )

is getting the wrong answer, but I don't know why. I can figure
out how set some kind of flag or something, but it seems to me
there should be a neat solution.
 
P

Paul Lalli

Lars Eighner said:
sub listdbs {
my @list = undef;

This almost certainly is not doing what you think it's doing. This is
setting @list to be an array containing exactly one element - the
undefined value.

The correct way to initialize an array to the empty list is:
my @list = ();

However, this is wholly unnecessary, as the empty list is the default
value of an array, so this will work fine:

my @list;

Hope this helps,
Paul Lalli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,164
Messages
2,570,898
Members
47,439
Latest member
shasuze

Latest Threads

Top