This code is giving me a Global Symbol requires explicit package name error. It's throwing it on the second time $user is defined. Below the code is the error. I don't understand the reasoning behind $user not having one. I'm trying to add to the hash that's returned.
my $self = shift;
my %json = ('err' => 0, 'msg' => '');
my $user = Order2016::get_orders($self->usernum); # Returns Hash
# Query to grab session history data
my $sql = "select rate.duration, rate.price, rate.description, rate.active, order.user_id, order.quantity, order.add_date, order.modify_date, order.end_date, order.last_bill, order.next_bill, item.*
from rate, order, item
where order.user_id = ?
and order.rate_id = rate.id
and rate.item_id = item.id";
my $query = new SQL($sql, $self->usernum);
my $hist = $query->GetRecordsAsHashRef();
$user{'uid'} = $self->usernum;
$self->Print(to_json($user));
Global symbol "%user" requires explicit package name at /devroot/depot/wxtap/deploy/scripts//Account.pm line 1340.
Compilation failed in require at /usr/lib/perl5/Apache2/porting.pm line 90.
I suspect that $user is a hash reference, not a hash. To use it, you need to dereference it first (using the -> operator):
$user->{uid} = $self->usernum;
This could also be written as:
$$user{uid} = ...;
...but that's far less common, and it's much more idiomatic to use the former method.
Please try $user->{'uid'}.
$user is being used as a reference here.
Related
# Object.pm
sub update {
$table = $self->DB_TABLE;
...
}
The update function is triggered when a value is updated and seems to be executed multiple times by other files whose relevant parts look like:
# Status.pm
use constant DB_TABLE => 'Status';
# Flag.pm
use constant DB_TABLE => 'flag';
I don't know the inner workings of this project, but modified Flag.pm and Object.pm as below because I need to use a different table for updating flag.
# Flag.pm
use constant DB_TABLE => 'flag';
use constnat DB_UPDATE_TABLE => '<Table to use when updating flag>';
# Object.pm
sub update {
my $table = undef;
if($self->DB_UPDATE_TABLE) {
$table = $self->DB_UPDATE_TABLE;
} else {
$table = $self->DB_TABLE;
}
}
When I triggered sub update, I get
Can't locate object method "DB_UPDATE_TABLE" via package "<Status.pm>" at Object.pm.
Is there any way I can check if DB_UPDATE_TABLE exists in each file without error? I can add the following line to Status.pm, but there are a couple dozen of files like Status.pm.
use constant DB_UPDATE_TABLE => '';
I don't know why it is $self->DB_TABLE not $self->{DB_TABLE} but with the assumption that it is a method... tried the following, but it also had its own error.
if( my $ref = eval { $self->can( DB_UPDATE_TABLE ) } ) {
$table = $self->DB_UPDATE_TABLE;
} else {
$table = $self->DB_TABLE;
}
Bareword "DB_UPDATE_TABLE" not allowed while "strict subs" in use at Object.pm => I couldn't find the part to set 'strict subs'
Super close!
$self->can( DB_UPDATE_TABLE )
should be
$self->can("DB_UPDATE_TABLE")
I am very new to Perl and was just assigned the quick task to change the reCAPTCHA to reCAPTCHA v2.
On my local machine this works fine, however when I push the new version of the login form to the webhost, the form does not seem to work. I get the following error:
AH01215: Can't use string ("") as a HASH ref while "strict refs" in use at login_new.cgi line 68, line 1.: [........]
The code snippet is based on the documentation I found here: https://metacpan.org/pod/Captcha::reCAPTCHA::V2
And according to the error log my error is somewhere in here (line 68):
if ($submit) {
my $response = $cgi->param('g-recaptcha-response');
my $result = $captcha->verify($captcha_private_key, $response );
if ($result->{success}) # This is line 68
{....}
This is quite confusing to me, especially since it is working on my local machine. Could you please help? Best regards and thank you in advance!
The Verify Function has a bug. I just looked at the implementation. in case that "$res" isn't 'successful' it wont give you back the wanted hash reference.
As a quick workaround I would check if your my $result is equal to "" if thats the case the verify function failed.
In the long run you should probably submit that bug to the creator of the module.
disclaimer: I havent downloaded the module and just looked at the source without actually trying my workaround so take it with a grain of salt and try it in a safe environment first
sub verify {
my ($self, $secret, $response, $remoteip) = #_;
# ... more code here, removed for better readability
my $res = $self->{ua}->post_form(
$self->{verify_api},
$params
);
if ($res->{success}) {
my $content = decode_json $res->{content};
if ($content->{success}){
return { success => 1 };
} else {
return { success => 0, error_codes => $content->{'error-codes'} };
}
}
}
I have a perl code like this:
use constant OPERATING_MODE_MAIN_ADMIN => 'super_admin';
use constant OPERATING_MODE_ADMIN => 'admin';
use constant OPERATING_MODE_USER => 'user';
sub system_details
{
return {
operating_modes => {
values => [OPERATING_MODE_MAIN_ADMIN, OPERATING_MODE_ADMIN, OPERATING_MODE_USER],
help => {
'super_admin' => 'The system displays the settings for super admin',
'admin' => 'The system displays settings for normal admin',
'user' => 'No settings are displayed. Only user level pages.'
}
},
log_level => {
values => [qw(FATAL ERROR WARN INFO DEBUG TRACE)],
help => "http://search.cpan.org/~mschilli/Log-Log4perl-1.49/lib/Log/Log4perl.pm#Log_Levels"
},
};
}
How will I access the "value" fields and "help" fields of each key from another subroutine? Suppose I want the values of operating_mode alone or log_level alone?
The system_details() returns a hashref, which has two keys with values being hashrefs. So you can dereference the sub's return and assign into a hash, and then extract what you need
my %sys = %{ system_details() };
my #loglevel_vals = #{ $sys{log_level}->{values} };
my $help_msg = $sys{log_level}->{help};
The #loglevel_vals array contains FATAL, ERROR etc, while $help_msg has the message string.
This makes an extra copy of a hash while one can work with a reference, as in doimen's answer
my $sys = system_details();
my #loglevel_vals = #{ $sys->{log_level}->{values} };
But as the purpose is to interrogate the data in another sub it also makes sense to work with a local copy, what is generally safer (against accidentally changing data in the caller).
There are modules that help with deciphering complex data structures, by displaying them. This helps devising ways to work with data. Often quoted is Data::Dumper, which also does more than show data. Some of the others are meant to simply display the data. A couple of nice ones are Data::Dump and Data::Printer.
my $sys = system_details;
my $log_level = $sys->{'log_level'};
my #values = #{ $log_level->{'values'} };
my $help = $log_level->{'help'};
If you need to introspect the type of structure stored in help (for example help in operating_mode is a hash, but in log_level it is a string), use the ref builtin func.
I am using Geo::IP to perform location lookups on ip addresses. Everything works fine until I come across an ip address which is not in the geo ip lookup database and the program shuts abruptly giving this error
Can't call method "city" on an undefined value at script.pl line 16.
Current code looks like this
$gi = Geo::IP->open("/usr/local/share/GeoIP/GeoLiteCity.dat", GEOIP_STANDARD);
my $record = $gi->record_by_addr($key);
my $city= $record->city;
Any suggestions on how I can by pass this? It works perfectly fine until it hits an ip address that isn't defined within that module.
Looking at the Geo::IP source, if the IP address is not in the database, it returns undef. Therefore, to bypass the problem, you can do:
my $record = $gi->record_by_addr($key);
## check that $record is defined
if ($record) {
my $city= $record->city;
...
}
else {
# issue an error message if wanted
warn "No record found for $key";
}
Relevant code from the Geo::IP source:
The function you're using is record_by_addr. From the source, record_by_addr is an alias for get_city_record_as_hash (see perlref for the syntax used to create an 'alias' for a function):
*record_by_addr = \&get_city_record_as_hash;
The code for get_city_record_as_hash is as follows:
#this function returns the city record as a hash ref
sub get_city_record_as_hash {
my ( $gi, $host ) = #_;
my %gir;
#gir{qw/ country_code country_code3 country_name region city
postal_code latitude longitude dma_code area_code
continent_code region_name metro_code / } =
$gi->get_city_record($host);
return defined($gir{latitude}) ? bless( \%gir, 'Geo::IP::Record' ) : undef;
}
This code runs get_city_record using $host, the IP address you supplied, as the argument. If get_city_record finds a record, the data it returns populates the %gir hash. The last line of the sub uses the [ternary form of if-else] to evaluate whether getting the record was successful, and to return the appropriate result. It checks whether $gir{latitude} is defined, and if it is, it creates and returns a Geo::IP::Record object from it (which you can query with methods like city, etc.). If it isn't, it returns undef.
A simpler way to view the last line would be this:
# is $gir{latitude} defined?
if (defined ($gir{latitude})) {
# yes: create a Geo::IP::Record object with the data in %gir
# return that object
return bless( \%gir, 'Geo::IP::Record' )
}
else {
# no: return undefined.
return undef;
}
I'd suggest that you need Data::Dumper here, to tell you what's going on with $record. I would guess that record_by_addr($key); is the root of your problems, and that because $key is in some way bad, $record is undefined.
This would thus be fixed:
use Data::Dumper;
print Dumper \$record;
I'm guessing $record will be undefined, and therefore:
next unless $record;
will skip it.
I've been banging my head over this issue for about 5 hours now, I'm really frustrated and need some assistance.
I'm writing a Perl script that pulls jobs out of a MySQL table and then preforms various database admin tasks. The current task is "creating databases". The script successfully creates the database(s), but when I got to generating the config file for PHP developers it blows up.
I believe it is an issue with referencing and dereferencing variables, but I'm not quite sure what exactly is happening. I think after this function call, something happens to
$$result{'databaseName'}. This is how I get result: $result = $select->fetchrow_hashref()
Here is my function call, and the function implementation:
Function call (line 127):
generateConfig($$result{'databaseName'}, $newPassword, "php");
Function implementation:
sub generateConfig {
my($inName) = $_[0];
my($inPass) = $_[1];
my($inExt) = $_[2];
my($goodData) = 1;
my($select) = $dbh->prepare("SELECT id FROM $databasesTableName WHERE name = '$inName'");
my($path) = $documentRoot.$inName."_config.".$inExt;
$select->execute();
if ($select->rows < 1 ) {
$goodData = 0;
}
while ( $result = $select->fetchrow_hashref() )
{
my($insert) = $dbh->do("INSERT INTO $configTableName(databaseId, username, password, path)".
"VALUES('$$result{'id'}', '$inName', '$inPass', '$path')");
}
return 1;
}
Errors:
Use of uninitialized value in concatenation (.) or string at ./dbcreator.pl line 142.
Use of uninitialized value in concatenation (.) or string at ./dbcreator.pl line 154.
Line 142:
$update = $dbh->do("UPDATE ${tablename}
SET ${jobStatus}='${newStatus}'
WHERE id = '$$result{'id'}'");
Line 154:
print "Successfully created $$result{'databaseName'}\n";
The reason I think the problem comes from the function call is because if I comment out the function call, everything works great!
If anyone could help me understand what's going on, that would be great.
Thanks,
p.s. If you notice a security issue with the whole storing passwords as plain text in a database, that's going to be addressed after this is working correctly. =P
Dylan
You do not want to store a reference to the $result returned from fetchrow_hashref, as each subsequent call will overwrite that reference.
That's ok, you're not using the reference when you are calling generate_config, as you are passing data in by value.
Are you using the same $result variable in generate_config and in the calling function? You should be using your own 'my $result' in generate_config.
while ( my $result = $select->fetchrow_hashref() )
# ^^ #add my
That's all that can be said with the current snippets of code you've included.
Some cleanup:
When calling generate_config you are passing by value, not by reference. This is fine.
you are getting an undef warning, this means you are running with 'use strict;'. Good!
create lexical $result within the function, via my.
While $$hashr{key} is valid code, $hashr->{key} is preferred.
you're using dbh->prepare, might as well use placeholders.
sub generateConfig {
my($inName, inPass, $inExt) = #_;
my $goodData = 1;
my $select = $dbh->prepare("SELECT id FROM $databasesTableName WHERE name = ?");
my $insert = $dbh->prepare("
INSERT INTO $configTableName(
databaseID
,username
,password
,path)
VALUES( ?, ?, ?, ?)" );
my $path = $documentRoot . $inName . "_config." . $inExt;
$select->execute( $inName );
if ($select->rows < 1 ) {
$goodData = 0;
}
while ( my $result = $select->fetchrow_hashref() )
{
insert->execute( $result->{id}, $inName, $inPass, $path );
}
return 1;
}
EDIT: after reading your comment
I think that both errors have to do with your using $$result. If $result is the return value of fetchrow_hashref, like in:
$result = $select->fetchrow_hashref()
then the correct way to refer to its values should be:
print "Successfully created " . $result{'databaseName'} . "\n";
and:
$update = $dbh->do("UPDATE ${tablename}
SET ${jobStatus}='${newStatus}'
WHERE id = '$result{'id'}'");
OLD ANSWER:
In function generateConfig, you can pass a reference in using this syntax:
generateConfig(\$result{'databaseName'},$newPassword, "php");
($$ is used to dereference a reference to a string; \ gives you a reference to the object it is applied to).
Then, in the print statement itself, I would try:
print "Successfully created $result->{'databaseName'}->{columnName}\n";
indeed, fetchrow_hashref returns a hash (not a string).
This should fix one problem.
Furthermore, you are using the variable named $dbh but you don't show where it is set. Is it a global variable so that you can use it in generateConfig? Has it been initialized when generateConfig is executed?
This was driving me crazy when I was running hetchrow_hashref from Oracle result set.
Turened out the column names are always returned in upper case.
So once I started referencing the colum in upper case, problem went away:
insert->execute( $result->{ID}, $inName, $inPass, $path );