美思 技術雜談: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.

```perl
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.)

```perl
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.
關於作者

身為資訊領域碩士,美思認為開發應用程式的目的是為社會帶來價值。如果在這個過程中該軟體能成為永續經營的項目,那就是開發者和使用者雙贏的局面。

美思喜歡用開源技術來解決各式各樣的問題,但必要時對專有技術也不排斥。閒暇之餘,美思將所學寫成文章,放在這個網站上和大家分享。