All tied() Up
A sister function of tie() is Perl's tied() function. By using this function, you can access a reference to the underlying object. Expanding this example class, you might want to add the flexibility to use a second password file midway in your program. Instead of creating a new tied object, you can change your existing one like so:
tied(%hash)->newPwdFile('/usr/local/apache/.passwds');
Which yields the same result as:
$obj = tie(%hash, 'Tie::Class', 'rw'); $obj->newPwdFile('/usr/local/apache/.passwds');
This (explicitly) calls the method newPwdFile() on the underlying tied object and allows you to use your object's methods on the new file. This is what the newPwdFile() method could look like:
sub newPwdFile { my $self = shift; $self->{PATH} = @_ ? shift : die "No new file given"; unless (-e $self->{PATH}) { if ($self->{CLOBBER}) { unless (open(FH,">$self->{PATH}")) { croak("Can't create $self->{PATH}: $!");} } else { croak("$self->{PATH} does not exist"); } } close FH; my ($line, $id, $pass, @lines); foreach $line (@lines) { ($id, $pass) = split(/\:/,$line); $self->{CURRENT}{$id} = $pass; } }