Michelle Chen 技術雜談:Show Class Name in Perl

Facebook Twitter LinkedIn LINE Skype EverNote GMail Yahoo Email

In Perl, you do not need to declare the type of a variable in advance. Sometimes, it is confusing because you do not know the type of the variable and you do not know what method to use. By using ref with a object, you can know the class (or type) of the object.

Say we want to extract some data from some xml files. XML::LibXML is Perl binding for libxml2, the XML C parser and toolkit of Gnome. Libxml2 is fast, stable and reliable. However, there are several related class in XML::LibXML. If you did not know which class the object is, you are unable to use it effectively. Let's check the type of $doc.

# Assume our xml file in the location of $file...
my $doc = XML::LibXML->load_xml(location => $file);
print ref($doc), "\n";
{{< / highlight >}}

Now, we know that $doc is a XML::LibXML::Document object.  We can get a list of nodes by getElementsByTagName method.

my @nodes = $doc->getElementsByTagName('a');
print ref($nodes[0]), "\n";
{{< / highlight >}}

We are aware that $nodes[0] is a XML::LibXML::Element object.  We can get the attribute value by getAttribute method and the content by textContent method.  (XML::LibXML::Element inherits from XML::LibXML::Node.  You can know that by reading the module document from CPAN site.)

for my $n (@nodes) {
    my $text = $n->textContext;
    my $type = $n->getAttribute('type');
    print "$text $type\n";
{{< / highlight >}}

Finally, we can extract needed data from XML files.  You should still read the documents on CPAN site.  However, `ref` can give you some hints about objects and classes.