How this code works? $" is the separator used when arrays are extrapolated in certain contexts (like in say "@array"), tie-ing it to 'main' means that it will be implemented in the scope of the main program. I'm not sure about bless\my$i and what ${$_[0]} is referring to when invoked in FETCH.
Give a man a fish and you feed him for a day. Give him a fishnet and you feed him for a lifetime. Ooops! Wait a minute! What if the fishnet brakes down? He will ask for an other fishnet or worse starve to death. Better yet to teach him how to make a fishnet. But what if he forgets how to make a fishnet? It is better to teach him where to look for knowledge on how to make a fishnet. But this can also go wrong. So ultimately it is best just telling him: 'Help yourself, stupid!'
| [reply] [d/l] [select] |
When you tie a variable, the TIE* method, in this case TIESCALAR, has to return an object. An object is nothing more than a blessed reference. \my $i is a reference to the variable $i. bless blesses its argument. If bless is given just one argument, it blesses the reference to the current package.
The first argument to the FETCH method is the object returned from bless. $_[0] is the first argument of a method, and ${EXPRESSION THAT RETURNS A SCALAR REFERENCE} is a way to dereference a scalar reference. So, you get back the $i.
| [reply] [d/l] [select] |
I was confused because I've thought that explicitly blessing with a class name was a must. However it is just a good practice becoming significant with inheritance (which is not the case here).
Give a man a fish and you feed him for a day. Give him a fishnet and you feed him for a lifetime. Ooops! Wait a minute! What if the fishnet brakes down? He will ask for an other fishnet or worse starve to death. Better yet to teach him how to make a fishnet. But what if he forgets how to make a fishnet? It is better to teach him where to look for knowledge on how to make a fishnet. But this can also go wrong. So ultimately it is best just telling him: 'Help yourself, stupid!'
| [reply] [d/l] |
tie, perltie
Update: What happens is that the main package is (ab)used as a class implementing a tied scalar for $". Whenever perl wants to use the value of the tied scalar $", it calls the object method FETCH instead, in this case, main::FETCH. And that method returns either "=" or "&", depending on how often it was called before. The modulo operator % switches between the two values with every call. To construct the object on which FETCH will be invoked, tie calls the TIESCALAR class method that returns a blessed reference to a scalar value, that value is used to count the calls inside FETCH.
Alexander
--
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
| [reply] [d/l] [select] |