in reply to Re^3: chunking up texts correctly for online translation
in thread chunking up texts correctly for online translation
Edit: 2 problems with this: 1) use My::Module; breaks things when the package is actually implemented in same file, so comment that out. 2) wrong order ot bless. The correct is bless $self, $class;, I use bless $self => $class; to be reminded of the correct order.
package My::Module; sub new { my ( $class, $param_hr ) = @_; $param_hr = {} unless defined $param_hr; my $self = { # hashref or arrayref key => 0, format => 0, #... }; bless $self => $class; # now your hash is an object of class $clas +s. if( exists $param_hr->{'key'} ){ $self->key($param_hr->{'key'}) } else { warn "param 'key' is required."; return undef } return $self; # return the hash, sorry now blessed into a class in +stance, hallelujah } # get or set the key sub key { my $self = $_[0]; my $akey = $_[1]; # optional key print "you called key() method on object '$self'\n"; if( defined $akey ){ print "key() : changing key to '$akey'\n"; $self->{'key'} = $akey; } return $self->{'key'}; } 1; package main; # uncomment only if My::Module is in separate file: #use My::Module; # the notation module->new adds "module" as the first argument to the +new() params. # so here is how $class is set in your question, although YOU dont pas +s class, Perl does. my $mod = My::Module->new({ 'key' => 123, }); die unless defined $mod; # the same notation applies when calling the method # Perl passes the object ref ($self=$mod) to the method as a first par +am print "my key: ".$mod->key()."\n";
Sometimes defining constants via Readonly or otherwise is useful
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^5: chunking up texts correctly for online translation
by Aldebaran (Curate) on Jul 01, 2019 at 22:15 UTC | |
by bliako (Abbot) on Jul 01, 2019 at 23:21 UTC |