uninitialized value in substitution iterator

A

Aberrant

What I'm trying to do is take %%variable%% in a file and replace it
with data returned by the subroutine substitute(). The code I have
looks like this:

$data =~ s/%%([^%]*)%%/&substitute($1)/ge;

And it does exactly what I want, but it also fills up my error log
with this:

"Use of uninitialized value in substitution iterator"

Can someone shed some light on this? How can I get around the warning?
Or rather, why is it being generated and how can I do what I want and
make perl happy? Thanks,

Abe
 
G

Gunnar Hjalmarsson

Aberrant said:
What I'm trying to do is take %%variable%% in a file and replace it
with data returned by the subroutine substitute(). The code I have
looks like this:

$data =~ s/%%([^%]*)%%/&substitute($1)/ge; -------------------------^
redundant

And it does exactly what I want, but it also fills up my error log
with this:

"Use of uninitialized value in substitution iterator"

Can someone shed some light on this?

The file probably includes variables that are unknown by the
substitute() function. You can for instance do something like this:

sub substitute {
my $key = shift;
my %vars = (
var1 => 'aaa',
var2 => 'bbb',
...
);

if ( $vars{$key} ) {
$vars{$key};
} else {
warn "Unknown template variable: $key";
"%%$key%%";
}
}
 
P

public

Gunnar said:
$data =~ s/%%([^%]*)%%/&substitute($1)/ge;
-------------------------^
redundant

What's redundant, the ampersand? Depending on how the text is displayed
the caret is pointing to parentheses.
The file probably includes variables that are unknown by the
substitute() function. You can for instance do something like this:

Thanks, that was the problem! I had this:

sub substitute
{
my $var = shift;
if (exists($subs->{$var}) && $subs->{$var} eq "readPage") {
return readPage($var);
} elsif (ref($subs->{$var}) eq "CODE") {
return &{$subs->{$var}};
} else {
return $subs->{$var};
}
}

and I changed it to this (last few lines changed):

sub substitute
{
my $var = shift;
if (exists($subs->{$var}) && $subs->{$var} eq "readPage") {
return readPage($var);
} elsif (ref($subs->{$var}) eq "CODE") {
return &{$subs->{$var}};
} elsif (exists($subs->{$var})) {
return $subs->{$var};
} else {
return "";
}
}


No more warnings, I never realized I was returning undef to s/// like
that.
 

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

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,272
Latest member
MaricruzDu

Latest Threads

Top