Soft refs problem with cgi - soft ref appears empty :-(


A

ade0

Hi Group,

I'm a relative cgi newbie. In the script below, I am trying to cycle
through 3 variables using a loop to create a soft reference for each,
and print the contents of each reference.

When I print the dereferenced value, it is always empty - but when I
print the variables themselves ($p0_mount etc), they contain the
correct values.

Can anybody see what I'm doing wrong.

Thanks
Adrian


#!/usr/bin/perl -wT
use strict;
use CGI qw:)standard);
use CGI::Carp qw(fatalsToBrowser);

my ($ref,$p0_mount,$p1_mount,$p2_mount,$q,$val);

$ENV{'PATH'}="/bin:/usr/bin";

print header, start_html("Test Soft Refs"), h1("Test Soft Refs");
$q=new CGI;
if ($q->param()) { # the form has already been filled out
# Read in parameters
$p0_mount=$q->param("p0_mount");
$p1_mount=$q->param("p1_mount");
$p2_mount=$q->param("p2_mount");
{
no strict 'refs';
for $val (0,1,2) {
# Create p0_mount, p1_mount, p2_mount etc
$ref="p${val}_mount";
# Ref in the following line always empty
print "Ref for value $val=$$ref",p;
}
print hr;
}
# The following provides correct values
print "Ref for value 0=$p0_mount",p,
"Ref for value 1=$p1_mount",p,
"Ref for value 2=$p2_mount",p,
hr;
} else {
print start_form;
print h2("Test soft refs");
print $q->textfield(-name=>'p0_mount',-value=>'p0');
print $q->textfield(-name=>'p1_mount',-value=>'p1');
print $q->textfield(-name=>'p2_mount',-value=>'p2');

print p(submit("Submit"),reset("clear"));
print end_form(), hr();
}
print end_html;


Script provides output like this:
Ref for value 0=
Ref for value 1=
Ref for value 2=
-------------------------------------------------------------------Ref
for value 0=p0
Ref for value 1=p1
Ref for value 2=p2
 
Ad

Advertisements

G

Gunnar Hjalmarsson

ade0 said:
In the script below, I am trying to cycle
through 3 variables using a loop to create a soft reference for each,
and print the contents of each reference.

When I print the dereferenced value, it is always empty - but when I
print the variables themselves ($p0_mount etc), they contain the
correct values.

Can anybody see what I'm doing wrong.

Answer 1:
You are using soft references when you easily could replace them by
using e.g. a hash. For instance:

my %par = map { $_, $q->param("p${_}_mount") } 0,1,2;
for my $key (0,1,2) {
print "Value $key=$par{$key}",p;
}

Answer 2:
The $p0_mount etc. variables are my() declared, while they'd need to be
package globals.

Answer 3:
You didn't check the FAQ before posting here. The FAQ entry

perldoc -q "variable name"

provides both answer 1 and 2 above.
 

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

Top