February 2012
Intermediate to advanced
1184 pages
37h 17m
English
One of the nice things about variables is that they interpolate. One of the not-so-nice things about functions is that they don’t. You can use a tied array to make a function that can be interpolated. Suppose you want to interpolate random integers in a string. You can just say:
#!/usr/bin/perl
package RandInterp;
sub TIEARRAY { bless \my $self };
sub FETCH { int rand $_[1] };
package main;
tie @rand, "RandInterp";
for (1,10,100,1000) {
print "A random integer less than $_ would be $rand[$_]\n";
}
$rand[32] = 5; # Will this reformat our system disk?When run, this prints:
A random integer less than 1 would be 0 A random integer less than 10 would be 3 A random integer less than 100 would be 46 A random integer less than 1000 would be 755 Can't locate object method "STORE" via package "RandInterp" at foo line 10.
As you can see, it’s no big deal that we didn’t even implement
STORE. It just blows up like
normal.
Read now
Unlock full access