The Case of the Preferred Parent

In which Dupin expounds on inter-generational relationships.

"Well, Dupin," I exclaimed upon entering our rooms in Paris, "you seem more cheerful than when I left this morning. Using your own methods, I am forced to conclude that you have spent the day wrestling with and defeating some great problem."

"You presume too much, mon ami," he replied. "The pleasure is not only in the great problems. There are small problems that yet have a charm and piquancy of their own."

"Will you edify me by sharing your small problem then? The knowledge can be your Christmas gift to me."

"Most willingly," Dupin replied. "At a bistrot this afternoon, I fell into conversation with a gentleman who had an air of preoccupation. When I asked his trouble, he replied that he was not so much troubled as puzzled. He wished to display an HTTP::Response object, and was dissatisfied with his code."

"Well the code is simple enough," I said. "There is an as_string() method for that very thing."

"That was the source of his puzzlement, mon ami. The string produced by that method was almost what he wanted. The exact output he desired is provided by the superclass, HTTP::Message. But HTTP::Response overrides this to add the status line at the top."

"Well, that seems rather picky. Why was it important?"

"Some trivial reason that escapes me at the moment. He actually got what he wanted by using the substitution operator to strip the status line, but was troubled by the inelegance of this solution when the code existed to do exactly what he wanted."

"But why not just use SUPER::as_string(). Isn't that what it is for?"

"Certainment, mon ami, but his code was failing to locate the method."

"Now I'm puzzled. Isn't that how HTTP::Response implements as_string()?"

"Mais oui,, but you both have overlooked one small thing about SUPER::. It resolves the method name not with respect to the invocant's name space, but with respect to the name space in which it is used. So SUPER::, to do the correct thing, must be placed in the correct name space, thus:

package HTTP::Response {
    say $resp->SUPER::as_string();

Users of older Perls which do not support this syntax can simply place the package statement and the call inside a block.

As usual, I ask forgiveness from the shade of Edgar Allen Poe for the use of his character, and of French-speakers for any mangling of their language. In particular I may have omitted a circumflex in "bistrot".

I no longer remember why I wanted the HTTP::Message stringification on an HTTP::Response object, but it occurred to me that the solution to the problem might be one of those "obscure nugget of knowledge" things that makes the problem a good Dupin blog. Of course, this only works for the immediate parent, and a purist (or a paranoid!) might warn against the technique unless the parentage of the object is documented (which is true in this case).

Leave a comment

About Tom Wyant

user-pic I blog about Perl.