我想知道导入方法的内部工作。当我搜索相同的内容时,它只显示如何在perl中使用import,这是我不需要的。
答案 0 :(得分:3)
如果要提供import
方法,可以使用use Exporter qw( import );
方法。大多数人使用
use Exporter qw( );
our @ISA = 'Exporter';
或旧版
import
如果这是您要求的sub foo { ... }
方法,请参阅the module's documentation以获取更多信息。
另一方面,如果您在询问如何在命名空间中动态添加子例程,那么它只是将子参考指定给glob的问题。这意味着
BEGIN { *foo = sub { ... }; }
大致相当于
no strict qw( refs );
*{ $dst_pkg . '::' . $sub_name } = \&{ $src_pkg . '::' . $sub_name };
所以你想要
require 'rubygems'
require 'nokogiri'
require 'open-uri'
url = "http://alexa.com/siteinfo/example.com"
doc = Nokogiri::HTML(open(url))
# I am getting current global rank of website here
current_rank = doc.at_css("strong.metrics-data.align-vmiddle").text
答案 1 :(得分:2)
当我搜索相同内容时,它仅显示如何使用导入 perl,我不需要。我想知道内部的工作 导入方法。
如果您想了解内部结构,请检查内部结构,即来源。
以下是来自import
模块的Exporter
子例程。如果您不了解某些“关键字”,请查看文档和Google。如果您没有找到任何答案,请在此处询问。
sub import {
my $pkg = shift;
my $callpkg = caller($ExportLevel);
if ($pkg eq "Exporter" and @_ and $_[0] eq "import") {
*{$callpkg."::import"} = \&import;
return;
}
# We *need* to treat @{"$pkg\::EXPORT_FAIL"} since Carp uses it :-(
my $exports = \@{"$pkg\::EXPORT"};
# But, avoid creating things if they don't exist, which saves a couple of
# hundred bytes per package processed.
my $fail = ${$pkg . '::'}{EXPORT_FAIL} && \@{"$pkg\::EXPORT_FAIL"};
return export $pkg, $callpkg, @_
if $Verbose or $Debug or $fail && @$fail > 1;
my $export_cache = ($Cache{$pkg} ||= {});
my $args = @_ or @_ = @$exports;
if ($args and not %$export_cache) {
s/^&//, $export_cache->{$_} = 1
foreach (@$exports, @{"$pkg\::EXPORT_OK"});
}
my $heavy;
# Try very hard not to use {} and hence have to enter scope on the foreach
# We bomb out of the loop with last as soon as heavy is set.
if ($args or $fail) {
($heavy = (/\W/ or $args and not exists $export_cache->{$_}
or $fail and @$fail and $_ eq $fail->[0])) and last
foreach (@_);
} else {
($heavy = /\W/) and last
foreach (@_);
}
return export $pkg, $callpkg, ($args ? @_ : ()) if $heavy;
local $SIG{__WARN__} =
sub {require Carp; &Carp::carp} if not $SIG{__WARN__};
# shortcut for the common case of no type character
*{"$callpkg\::$_"} = \&{"$pkg\::$_"} foreach @_;
}
完整来源:https://metacpan.org/source/TODDR/Exporter-5.72/lib/Exporter.pm