你正在混合幾種不同的方式來處理模塊和對象 - 最後一個不起作用。
這裏是做工作的四種方法:
1 /我::模塊是一個圖書館。修剪不會導出。
$ cat My/Module.pm
package My::Module;
use strict;
use warnings;
sub trim {
my $str = shift;
$str =~ s{ \A \s+ }{}xms; # remove space from front of string
$str =~ s{ \s+ \z }{}xms; # remove space from end of string
return $str;
}
1;
$ cat test
#!/usr/bin/perl
use strict;
use warnings;
use My::Module;
# Note: No $ and :: not ->
print My::Module::trim(" \t hello world\t \t");
2/My :: Module是一個庫。修剪被導出。
$ cat My/Module.pm
package My::Module;
use strict;
use warnings;
use Exporter;
our @ISA = qw(Exporter);
our @EXPORT = qw(trim);
sub trim {
my $str = shift;
$str =~ s{ \A \s+ }{}xms; # remove space from front of string
$str =~ s{ \s+ \z }{}xms; # remove space from end of string
return $str;
}
1;
$ cat test
#!/usr/bin/perl
use strict;
use warnings;
use My::Module;
print trim(" \t hello world\t \t");
3/MyModule是一個類。修剪是一種類方法。
$ cat My/Module.pm
package My::Module;
use strict;
use warnings;
sub trim {
# Note class name passed as first argument
my $class = shift;
my $str = shift;
$str =~ s{ \A \s+ }{}xms; # remove space from front of string
$str =~ s{ \s+ \z }{}xms; # remove space from end of string
return $str;
}
1;
$ cat test
#!/usr/bin/perl
use strict;
use warnings;
use My::Module;
# Note: Not $ and -> not ::
print My::Module->trim(" \t hello world\t \t");
4/MyModule是一個類,trim是一個對象方法。
$ cat My/Module.pm
package My::Module;
use strict;
use warnings;
# Need a constructor (but this one does nothing useful)
sub new {
my $class = shift;
return bless {}, $class;
}
sub trim {
# Note: Object method is passed an object (which is ignored here)
my $self = shift;
my $str = shift;
$str =~ s{ \A \s+ }{}xms; # remove space from front of string
$str =~ s{ \s+ \z }{}xms; # remove space from end of string
return $str;
}
1;
$ cat test
#!/usr/bin/perl
use strict;
use warnings;
use My::Module;
my $trimmer = My::Module->new;
print $trimmer->trim(" \t hello world\t \t");
我認爲你試圖爲選項1.在這種情況下,我想我會建議選擇2
並回答你的最後一個問題。你正在得到那個錯誤,因爲你試圖調用一個未定義的變量($ My :: Module)的方法。
我傾向於把這些寫在正則表達式的,因爲我喜歡把評論內聯:)。我只是爲了舉例而忘了帶他們出去。 – heymatthew 2010-08-30 03:38:05
@ The Daemons Advocate,/ s和/ m與內嵌評論無關。那是/ x。 – cjm 2010-08-30 05:48:43