Can I execute a XPath query on previous result?
I have this xpath:
my #objDivRes = $objBrow->xpath('//div[#id="result"]/ol/div/li', all => 1);
but when I execute xpath function on previous result
my #objLink = $objDivRes[0]->MozRepl::RemoteObject::Methods::xpath('//div/h3/a');
I got an error:
MozRepl::RemoteObject: TypeError: doc.evaluate is not a function at test.pl
Is there an example? Thank you
Just use 'node' option to set up a subtree $mech->xpath( $query, %options )
Note dot in the beginning of the path, which means descendands of the context node
my #objDivRes = $objBrow->xpath('//div[#id="result"]/ol/div/li', all => 1);
my #objLink = $objBrow->xpath('.//div/h3/a', node => $objDivRes[0]);
Related
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.
I'm trying to get some scripting finished to deploy changes en masse to about 400 Cisco devices. I've got a perl script modified from MrAudit that's using Net::Telnet::Cisco and for the life of me, I can't figure out the named parameter component.
In the documentation, they have:
$ok = $obj->cmd($string);
$ok = $obj->cmd(String => $string,
[Output => $ref,]
[Prompt => $match,]
[Timeout => $secs,]
[Cmd_remove_mode => $mode,]);
#output = $obj->cmd($string);
#output = $obj->cmd(String => $string,
[Output => $ref,]
[Prompt => $match,]
[Timeout => $secs,]
[Cmd_remove_mode => $mode,]
[Normalize_cmd => $boolean,]);
And my code is:
$testString is the test command I'm running against the device, $userTest1 is an array being cast where I want the output to be stored.
$::OPENRTR->cmd(String=>$testString,[Timeout=>5,Output=>$userTest1,]);
And every single time, no matter which component I modify or try and write it a different way, I get a variation of the error:
Odd number of elements in hash assignment at(filename)
bad named parameter "ARRAY(0x2e46460)" given to Net::Telnet::Cisco::cmd() at mrAudit-TACACSMod.pl line 279
I know it has to be something simple, but it's just flying right by. Any help would be appreciated.
I think the square brackets in the documentation just show the arguments are optional, you shouldn't use them in real code:
$OPENRTR->cmd( String => $testString,
Timeout => 5,
Output => $userTest1);
I have a sub in a Perl module, Advancer.pm:
sub validate_extra {
my ($dbh, $customer_id, $site) = #_;
my $sth = $dbh->prepare(qq{
SELECT key
FROM master
WHERE
code = ?
AND set = ?
AND type_id = 2
ORDER BY customer_id DESC, site DESC
LIMIT 1
});
$sth->execute($customer_id, $site);
But when I call this module from a test (.t) I get an error:
Can't call method "prepare" on an undefined value at Advancer.pm line 511.
my $sth = $dbh->prepare(qq{
is line 511.
You're passing an undefined value for the first parameter to validate_extra.
Most obviously this would happen if your call was just
validate_extra();
but you may have passed the wrong variable by mistake, or perhaps the original connect has failed but gone unchecked:
my $dbh = DBI->connect('DBI:mysql:database=mydb', 'user', 'pass', {PrintError => 0});
validate_extra($dbh, $customer, $site);
In my Application_Model_DbTable_User, I have the following function:
public function deleteUser($username)
{
$this->delete('username = ' . (string) $username);
}
This function is being called from my AdminController, with this three lines of code.
$uname = $this->getRequest()->getParam('username');
$user = new Application_Model_DbTable_User();
$user->deleteUser($uname);
This error however, turns up.
Column not found: 1054 Unknown column 'test' in 'where clause'
With test being the user I am trying to delete.
This code is adapted from a previous code which deletes based on id, a INT field, which works perfectly fine. What am I doing wrong? I would be happy to give more detailed codes if needed. Thanks.
Your query isn't quoted:
$this->delete('username = ' . (string) $username);
This equates to:
WHERE username = test
If you use the where() method, it will do this for you:
$table->where('username = ?', $username);
Or (like the example in the docs):
$where = $table->getAdapter()->quoteInto('bug_id = ?', 1235);
$table->delete($where);
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 );