...

View Full Version : Can't call method "XX" error, please help noob



squeakers
07-16-2009, 03:12 PM
Hello Y'all, yes I'm a noob, and yes I'll probably only post a couple of times. I've been working on this perl script called yweather for almost a week now. It didnt work when I downloaded it, and it still doesnt work. I am NOT a programmer but after a week I've decided to turn to those that are. Here is the script:


#!/usr/bin/perl

#################################################################
# Yahoo Weather Rss Information Atomizer
# Version 0.7.1
# Loud-Soft.com
# Provided As Is
#################################################################

use strict;
use XML::XPath;
use LWP::Simple;
use XML::XPath::XMLParser;
use Getopt::Long;
use File::Copy;

#################################################################
# Variables
#################################################################
# Constants (Change these to localize)
my $zipcode = "60642";
my $unit = "F";
my $scripthome = "/Library/prlprograms/yweather.pl";
my $icondir = $scripthome."images/";
my $datadir = $scripthome."data/";
my $datafile = $datadir."weather.xml";
my $imagefile = $icondir."weather.png";

# Constants (Do not change these)
my $pre="yweather";
my $uri="http://xml.weather.yahoo.com/ns/rss/1.0";
my $url="http://xml.weather.yahoo.com/forecastrss?p=$zipcode&u=$unit";
my %data;
my $xp;

#################################################################
# Subroutines
#################################################################
# Print usage
sub usage {
print "Yahoo Weather Information\n\n";
print "Usage:\n";
print " ./yweather.pl -ct Displays current temperature\n\n";
print "Arguments: \n";
print " -lc City \n";
print " -lr Region\n";
print " -lt Country\n";
print " -cc Weather Code (used for images)\n";
print " -ct Current Temperature\n";
print " -cw Current Weather Description\n";
print " -cd Current Date\n";
print " -ah Current Humidity\n";
print " -av Current Visibilty\n";
print " -ap Current Barometric Pressure\n";
print " -ar Change in Barometric Pressure\n";
print " -sr Time of Sunrise\n";
print " -ss Time of Sunset\n";
print " -wc Current Wind Chill\n";
print " -wd Current Wind Direction\n";
print " -ws Current Wind Speed\n";
print " -ut Temperature Unit\n";
print " -ud Distance Unit\n";
print " -up Pressure Unit \n";
print " -us Speed Unit\n";
print " -fd1 Tomorrow's Day\n";
print " -fg1 Tomorrow's Date\n";
print " -fl1 Tomorrow's Low Temp\n";
print " -fh1 Tomorrow's High Temp\n";
print " -ft1 Tomorrow's Description\n";
print " -fc1 Tomorrow's Weather Code\n";
print " -fd2 Day After Tomorrow's Day\n";
print " -fg2 Day After Tomorrow's Date\n";
print " -fl2 Day After Tomorrow's Low Temp\n";
print " -fh2 Day After Tomorrow's High Temp\n";
print " -ft2 Day After Tomorrow's Description\n";
print " -fc2 Day After Tomorrow's Weather Code\n";
print " --copyimage Copy Appropriate Image to Current Image\n";
print " --update Update xml source file\n" ;
print " \n";
print "All data is returned without units. To get data with units,\n";
print "use a combination of commands.\n\n";
print "Example: (Displays Current temperature with unit)\n";
print " ./yweather.pl -ct && ./yweather.pl -ut\n";
}

# Print data
sub args{
my ($arg) = @_;
print $data{$arg} . "\n";
}

# Subroutine to update xml data from yahoo
sub update_weather {
LWP::Simple::getstore($url,$datafile);
}

# Subroutine to download images from yahoo
sub get_images {
my $imgurl = "http://l.yimg.com/a/i/us/nws/weather/gr/";
for (0..47) {
LWP::Simple::getstore($imgurl.$_."d.png",$icondir.$_."d.png");
LWP::Simple::getstore($imgurl.$_."n.png",$icondir.$_."n.png");
}
File::Copy::copy($icondir."0d.png", $imagefile);
}

# Parse XML
sub get_data {
my($element, $attribute, $index) = @_;
if ($index){$index=1;}

my $nodeset = $xp->find("//yweather:$element");
my $node = $nodeset->get_node($index);
$ret = $node->getAttribute($attribute);
return $ret;
}

# Copy correct image to the image define in $imagefile
sub copy_image {
my ($second, $minute, $hour, $dayOfMonth, $month,
$yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
my $night = $data{'ss'};
my $morning = $data{'sr'};
# my $condition = $data{'cc'};
my $imagesub;
if ($hour % 12){
if(($hour-12) < int(substr($night,0,1))){
$imagesub = "d";
}elsif(($minute) < int(substr($night,2,3))){
$imagesub = "d";
}else{
$imagesub = "n";
}
} else {
if(($hour) < int(substr($morning,0,1))){
$imagesub = "n";
}elsif(($minute) < int(substr($morning,2,3))){
$imagesub = "n";
}else{
$imagesub = "d";
}
}
File::Copy::copy($icondir.$data{'cc'}.$imagesub.".png", $imagefile)
or die "File ".$icondir.$data{'cc'}.$imagesub.".png"." cannot be copied. ".$data{'lr'};
}

#################################################################
# Check that files exist
#################################################################
#ensure directories exist
unless(-d $datadir){
mkdir $datadir;
}
unless(-d $icondir){
mkdir $icondir;
}

# Check if weather.xml exists
if (!(-e $datafile)){update_weather()}
$xp = XML::XPath->new(filename => $datafile);
$xp->set_namespace($pre, $uri);

# Check if images exist
if (!(-e $icondir."0d.png")){get_images()}

# Check if image exist
if (!(-e $imagefile)){copy_image()}


#################################################################
# Data Setup
#################################################################
# Location Information
$data{'lc'} = get_data("location","city");
$data{'lr'} = get_data("location","region");
$data{'lt'} = get_data("location","country");

# Current Weather Information
$data{'cc'} = get_data("condition","code");
$data{'ct'} = get_data("condition","temp");
$data{'cw'} = get_data("condition","text");
$data{'cd'} = get_data("condition","date");

# Current Atmosphere Information
$data{'ah'} = get_data("atmosphere","humidity");
$data{'av'} = get_data("atmosphere","visibility");
$data{'ap'} = get_data("atmosphere","pressure");
$data{'ar'} = get_data("atmosphere","rising");

# Todays Sunrise and sunset
$data{'sr'} = get_data("astronomy","sunrise");
$data{'ss'} = get_data("astronomy","sunset");

# Current wind information
$data{'wc'} = get_data("wind","chill");
$data{'wd'} = get_data("wind","direction");
$data{'ws'} = get_data("wind","speed");

# Unit information
$data{'ut'} = get_data("units","temperature");
$data{'ud'} = get_data("units","distance");
$data{'up'} = get_data("units","pressure");
$data{'us'} = get_data("units","speed");

# Forecast (Tomorrow)
$data{'fd1'} = get_data("forecast[1]","day");
$data{'fg1'} = get_data("forecast[1]","date");
$data{'fl1'} = get_data("forecast[1]","low");
$data{'fh1'} = get_data("forecast[1]","high");
$data{'ft1'} = get_data("forecast[1]","text");
$data{'fc1'} = get_data("forecast[1]","code");

# Forecast (Day after tomorrow)
$data{'fd2'} = get_data("forecast[2]","day");
$data{'fg2'} = get_data("forecast[2]","date");
$data{'fl2'} = get_data("forecast[2]","low");
$data{'fh2'} = get_data("forecast[2]","high");
$data{'ft2'} = get_data("forecast[2]","text");
$data{'fc2'} = get_data("forecast[2]","code");

#################################################################
# Parse arguments
#################################################################
if(($#ARGV + 1) == 1){
my $arg = substr($ARGV[0],1);
if ($data{$arg}){
args($arg);
} elsif($arg eq "-update"){
update_weather();
} elsif($arg eq "-copyimage"){
copy_image();
} else {
usage();
}
} else {
usage();
}

I've colored the problem area. I keep getting Can't call method "getAttribute" on an undefined value at ./yweather.pl line 114

I have no idea how to fix and make this a working code
PLEASE HELP
thanks

squeakers
07-16-2009, 04:14 PM
this is the link to what i'm trying to do.

http://lifehacker.com/5261449/yweather-puts-the-weather-on-your-os-x-desktop

Maybe this will provide some insight on whats wrong with the code

FishMonger
07-16-2009, 05:23 PM
The error message is telling you that $node is not defined, which means the line that assigned $node failed.

i.e., this line failed

my $node = $nodeset->get_node($index);

I have not used the XML::XPath module, but I suspect the problem might be due to the fact that $index is not being assigned a value. You might need to look at the source code of the module to see if the get_node() method requires a parameter and what does it return if it doesn't receive a parameter.

squeakers
07-16-2009, 05:35 PM
For a noob/nonprogrammer can you explain what you just said, or how to check.

Also the error comes up "getAttribute", but you mentioned it failed 1 lines above that

Sorry for being a noob

Thanks for the help

squeakers
07-16-2009, 05:53 PM
fixed title, sorry

FishMonger
07-16-2009, 06:03 PM
This is Object Orientated programming which can be difficult to understand, and even more difficult for me to try and explain.

$node is an object and "getAttribute" is one of its methods (also known as subroutines). However in this case, the assignment of $node failed so there is no "getAttribute" method/subroutine available.

Are you ready for some reading?

perlboot - Beginner's Object-Oriented Tutorial
http://perldoc.perl.org/perlboot.html

perltoot - Tom's object-oriented tutorial for perl
http://perldoc.perl.org/perltoot.html

squeakers
07-16-2009, 06:05 PM
i understand and i will read those links.

Are there any code additions or deletions to make this work (while I'm reading)??

FishMonger
07-16-2009, 06:10 PM
You could try changing (line 110):

if ($index){$index=1;}
to:

$index=1;

squeakers
07-17-2009, 06:10 PM
You could try changing (line 110):

if ($index){$index=1;}
to:

$index=1;

attempted this and got and error, program terminated

KevinADC
07-17-2009, 08:55 PM
I did not take a long hard look at your code, but it seems to me that $index is never defined and that is the source of your problem. You only ever send two arguments to the get_data subroutine but it expects three. So you check if $index has a true value:


if ($index){$index=1;}

which it never does so it remains an empty string. Then you use it to create an object:


my $node = $nodeset->get_node($index);

but evidently because $index has no value, the $node object never gets created, ipso-facto you can't call its method getAttribute.
But since I don't know which module the getAttribute method is imported from I can't look it up to see what value $index should have when you use it to create your $node object. It seems to me Fishmongers suggestion should have worked if a value of 1 is a legal value to send to the getAttribute method.

You can try:


if (!$index) {$index = 1;}

But I doubt it will work since it really does the same thing Fishmonger already suggested.

squeakers
07-18-2009, 06:16 AM
sorry double post by accident, cant delete

see below

squeakers
07-18-2009, 06:18 AM
I believe we are getting somewhere. I had the same thought, that some piece of information was not being created. Can you take a closer look at the code?

You also mention: "I don't know which module the getAttribute method is imported from I can't look it up to see what value $index should have when you use it to create your $node object" (sorry for not quoting). I dont know what you mean by module (noob)

I was trying to find a way to determine what information it is looking for or what information is/isnt being sent. Again, I didnt write the code, and I am not a programmer so this is turning out to be harder than I had anticipated.

Your help is greatly appreciated, thanks to all that contribute to getting this to work

squeakers
07-18-2009, 06:22 AM
you are correct, i made the changes suggested in still get the same erro

squeakers
07-18-2009, 06:37 AM
Could this be an issue with not having the correct URL to pull the rss feed from?

KevinADC
07-18-2009, 09:36 PM
I believe we are getting somewhere. I had the same thought, that some piece of information was not being created. Can you take a closer look at the code?

You also mention: "I don't know which module the getAttribute method is imported from I can't look it up to see what value $index should have when you use it to create your $node object" (sorry for not quoting). I dont know what you mean by module (noob)

I was trying to find a way to determine what information it is looking for or what information is/isnt being sent. Again, I didnt write the code, and I am not a programmer so this is turning out to be harder than I had anticipated.

Your help is greatly appreciated, thanks to all that contribute to getting this to work

These are the modules your script is using:

use XML::XPath;
use LWP::Simple;
use XML::XPath::XMLParser;
use Getopt::Long;
use File::Copy;


one of those is importing the getAttribute method, probably one of the XML modules. I have little to no experience with the XML modules so I can't help with their usage. You might want to take this over to www.perlmonks.com and hopefully someone there can help you out,

squeakers
07-22-2009, 05:49 AM
So in doing some looking into the XML parser, I discovered that i have a attribute node, and an element node, but no index node. Could this be my problem??? I thought i would try to determine what information is being pulled by the XML parser, when i discovered that "index" didnt exist. Still going strong after a week and a half, one would think i would have given up by now. Thanks to all that have and continue to help

Code for my XML Parser

# $Id: XMLParser.pm,v 1.49 2001/03/14 17:13:57 matt Exp $

package XML::XPath::XMLParser;

use strict;

use XML::Parser;
#use XML::XPath;
use XML::XPath::Node;
use XML::XPath::Node::Element;
use XML::XPath::Node::Text;
use XML::XPath::Node::Comment;
use XML::XPath::Node::PI;
use XML::XPath::Node::Attribute;
use XML::XPath::Node::Namespace;

my @options = qw(
filename
xml
parser
ioref
);

my ($_current, $_namespaces_on);
my %IdNames;

use vars qw/$xmlns_ns $xml_ns/;

$xmlns_ns = "http://www.w3.org/2000/xmlns/";
$xml_ns = "http://www.w3.org/XML/1998/namespace";

sub new {
my $proto = shift;
my $class = ref($proto) || $proto;
my %args = @_;
my %hash = map(( "_$_" => $args{$_} ), @options);
bless \%hash, $class;
}

sub parse {
my $self = shift;

$self->{IdNames} = {};
$self->{InScopeNamespaceStack} = [ {
'_Default' => undef,
'xmlns' => $xmlns_ns,
'xml' => $xml_ns,
} ];

$self->{NodeStack} = [ ];

$self->set_xml($_[0]) if $_[0];

my $parser = $self->get_parser || XML::Parser->new(
ErrorContext => 2,
ParseParamEnt => 1,
);

$parser->setHandlers(
Init => sub { $self->parse_init(@_) },
Char => sub { $self->parse_char(@_) },
Start => sub { $self->parse_start(@_) },
End => sub { $self->parse_end(@_) },
Final => sub { $self->parse_final(@_) },
Proc => sub { $self->parse_pi(@_) },
Comment => sub { $self->parse_comment(@_) },
Attlist => sub { $self->parse_attlist(@_) },
);

my $toparse;
if ($toparse = $self->get_filename) {
return $parser->parsefile($toparse);
}
else {
return $parser->parse($self->get_xml || $self->get_ioref);
}
}

sub parsefile {
my $self = shift;
my ($filename) = @_;
$self->set_filename($filename);
$self->parse;
}

sub parse_init {
my $self = shift;
my $e = shift;
my $document = XML::XPath::Node::Element->new();
my $newns = XML::XPath::Node::Namespace->new('xml', $xml_ns);
$document->appendNamespace($newns);
$self->{current} = $self->{DOC_Node} = $document;
}

sub parse_final {
my $self = shift;
return $self->{DOC_Node};
}

sub parse_char {
my $self = shift;
my $e = shift;
my $text = shift;

my $parent = $self->{current};

my $last = $parent->getLastChild;
if ($last && $last->isTextNode) {
# append to previous text node
$last->appendText($text);
return;
}

my $node = XML::XPath::Node::Text->new($text);
$parent->appendChild($node, 1);
}

sub parse_start {
my $self = shift;
my $e = shift;
my $tag = shift;

push @{ $self->{InScopeNamespaceStack} },
{ %{ $self->{InScopeNamespaceStack}[-1] } };
$self->_scan_namespaces(@_);

my ($prefix, $namespace) = $self->_namespace($tag);

my $node = XML::XPath::Node::Element->new($tag, $prefix);

my @attributes;
for (my $ii = 0; $ii < $#_; $ii += 2) {
my ($name, $value) = ($_[$ii], $_[$ii+1]);
if ($name =~ /^xmlns(:(.*))?$/) {
# namespace node
my $prefix = $2 || '#default';
# warn "Creating NS node: $prefix = $value\n";
my $newns = XML::XPath::Node::Namespace->new($prefix, $value);
$node->appendNamespace($newns);
}
else {
my ($prefix, $namespace) = $self->_namespace($name);
undef $namespace unless $prefix;

my $newattr = XML::XPath::Node::Attribute->new($name, $value, $prefix);
$node->appendAttribute($newattr, 1);
if (exists($self->{IdNames}{$tag}) && ($self->{IdNames}{$tag} eq $name)) {
# warn "appending Id Element: $val for ", $node->getName, "\n";
$self->{DOC_Node}->appendIdElement($value, $node);
}
}
}

$self->{current}->appendChild($node, 1);
$self->{current} = $node;
}

sub parse_end {
my $self = shift;
my $e = shift;
$self->{current} = $self->{current}->getParentNode;
}

sub parse_pi {
my $self = shift;
my $e = shift;
my ($target, $data) = @_;
my $node = XML::XPath::Node::PI->new($target, $data);
$self->{current}->appendChild($node, 1);
}

sub parse_comment {
my $self = shift;
my $e = shift;
my ($data) = @_;
my $node = XML::XPath::Node::Comment->new($data);
$self->{current}->appendChild($node, 1);
}

sub parse_attlist {
my $self = shift;
my $e = shift;
my ($elname, $attname, $type, $default, $fixed) = @_;
if ($type eq 'ID') {
$self->{IdNames}{$elname} = $attname;
}
}

sub _scan_namespaces {
my ($self, %attributes) = @_;

while (my ($attr_name, $value) = each %attributes) {
if ($attr_name eq 'xmlns') {
$self->{InScopeNamespaceStack}[-1]{'_Default'} = $value;
} elsif ($attr_name =~ /^xmlns:(.*)$/) {
my $prefix = $1;
$self->{InScopeNamespaceStack}[-1]{$prefix} = $value;
}
}
}

sub _namespace {
my ($self, $name) = @_;

my ($prefix, $localname) = split(/:/, $name);
if (!defined($localname)) {
if ($prefix eq 'xmlns') {
return '', undef;
} else {
return '', $self->{InScopeNamespaceStack}[-1]{'_Default'};
}
} else {
return $prefix, $self->{InScopeNamespaceStack}[-1]{$prefix};
}
}

sub as_string {
my $node = shift;
$node->toString;
}

sub get_parser { shift->{_parser}; }
sub get_filename { shift->{_filename}; }
sub get_xml { shift->{_xml}; }
sub get_ioref { shift->{_ioref}; }

sub set_parser { $_[0]->{_parser} = $_[1]; }
sub set_filename { $_[0]->{_filename} = $_[1]; }
sub set_xml { $_[0]->{_xml} = $_[1]; }
sub set_ioref { $_[0]->{_ioref} = $_[1]; }

1;

__END__

=head1 NAME

XML::XPath::XMLParser - The default XML parsing class that produces a node tree

=head1 SYNOPSIS

my $parser = XML::XPath::XMLParser->new(
filename => $self->get_filename,
xml => $self->get_xml,
ioref => $self->get_ioref,
parser => $self->get_parser,
);
my $root_node = $parser->parse;

=head1 DESCRIPTION

This module generates a node tree for use as the context node for XPath processing.
It aims to be a quick parser, nothing fancy, and yet has to store more information
than most parsers. To achieve this I've used array refs everywhere - no hashes.
I don't have any performance figures for the speedups achieved, so I make no
appologies for anyone not used to using arrays instead of hashes. I think they
make good sense here where we know the attributes of each type of node.

=head1 Node Structure

All nodes have the same first 2 entries in the array: node_parent
and node_pos. The type of the node is determined using the ref() function.
The node_parent always contains an entry for the parent of the current
node - except for the root node which has undef in there. And node_pos is the
position of this node in the array that it is in (think:
$node == $node->[node_parent]->[node_children]->[$node->[node_pos]] )

Nodes are structured as follows:

=head2 Root Node

The root node is just an element node with no parent.

[
undef, # node_parent - check for undef to identify root node
undef, # node_pos
undef, # node_prefix
[ ... ], # node_children (see below)
]

=head2 Element Node

[
$parent, # node_parent
<position in current array>, # node_pos
'xxx', # node_prefix - namespace prefix on this element
[ ... ], # node_children
'yyy', # node_name - element tag name
[ ... ], # node_attribs - attributes on this element
[ ... ], # node_namespaces - namespaces currently in scope
]

=head2 Attribute Node

[
$parent, # node_parent - the element node
<position in current array>, # node_pos
'xxx', # node_prefix - namespace prefix on this element
'href', # node_key - attribute name
'ftp://ftp.com/', # node_value - value in the node
]

=head2 Namespace Nodes

Each element has an associated set of namespace nodes that are currently
in scope. Each namespace node stores a prefix and the expanded name (retrieved
from the xmlns:prefix="..." attribute).

[
$parent,
<pos>,
'a', # node_prefix - the namespace as it was written as a prefix
'http://my.namespace.com', # node_expanded - the expanded name.
]

=head2 Text Nodes

[
$parent,
<pos>,
'This is some text' # node_text - the text in the node
]

=head2 Comment Nodes

[
$parent,
<pos>,
'This is a comment' # node_comment
]

=head2 Processing Instruction Nodes

[
$parent,
<pos>,
'target', # node_target
'data', # node_data
]

=head1 Usage

If you feel the need to use this module outside of XML::XPath (for example
you might use this module directly so that you can cache parsed trees), you
can follow the following API:

=head2 new

The new method takes either no parameters, or any of the following parameters:

filename
xml
parser
ioref

This uses the familiar hash syntax, so an example might be:

use XML::XPath::XMLParser;

my $parser = XML::XPath::XMLParser->new(filename => 'example.xml');

The parameters represent a filename, a string containing XML, an XML::Parser
instance and an open filehandle ref respectively. You can also set or get all
of these properties using the get_ and set_ functions that have the same
name as the property: e.g. get_filename, set_ioref, etc.

=head2 parse

The parse method generally takes no parameters, however you are free to
pass either an open filehandle reference or an XML string if you so require.
The return value is a tree that XML::XPath can use. The parse method will
die if there is an error in your XML, so be sure to use perl's exception
handling mechanism (eval{};) if you want to avoid this.

=head2 parsefile

The parsefile method is identical to parse() except it expects a single
parameter that is a string naming a file to open and parse. Again it
returns a tree and also dies if there are XML errors.

=head1 NOTICES

This file is distributed as part of the XML::XPath module, and is copyright
2000 Fastnet Software Ltd. Please see the documentation for the module as a
whole for licencing information.

squeakers
07-22-2009, 05:51 AM
not really sure why i have smiles in my code :)

KevinADC
07-22-2009, 05:56 PM
because you are not using the code tags.

FishMonger
07-22-2009, 06:07 PM
Was there a question somewhere in here that I missed?

squeakers
07-22-2009, 08:53 PM
Was there a question somewhere in here that I missed?

yes there was a question. In looking at where the code fail, we have all decided it fails on the index line. I have posted the code for the XML Parser and there is no mention of index. I see an element and an attribute. IS this what is causing the failure???

sirisaac
08-15-2009, 09:39 PM
I got the same error, but after deleting "weather.xml" in the "data" folder, it works. I made a typo and this led to a wrong .xml-file.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum