Hi! Please consider following me on twitter: @hanekomu.
2008年09月24日
Dissecting the Moose
I have a few blog posts on Moose, in which I write about things I'm learning about Moose as I go along.
This page serves as an entry point into this list of posts.
- Dissecting the Moose Part 1
- Dissecting the Moose Part 2 - Pragmatic Goodness
- Dissecting the Moose Part 3 - Benchmarking Accessor Generators
- Dissecting the Moose Part 4 - Benchmarking Accessor Generators - Accessor Only
- Dissecting the Moose Part 5 - Accessor Generator Benchmarks Updated
Tags: Moose.
posted at: 11:37 | path: /articles | permalink | 0 comments | 0 trackbacks
Dissecting the Moose Part 2 - Pragmatic Goodness
The synopsis of Moose.pm has this innocent-looking line:
use Moose; # automatically turns on strict and warnings
Which begs the question: "How does that work?" In this blog post, I'll try to uncover some of the magic of Perl pragmata.
When you say:
use Moose;
according to perldoc -f use, that really means:
BEGIN { require Moose; Moose->import(LIST); }
But Moose does not have either an import() or an
unimport() subroutine. What's going on?
When loaded, that is, during the require() call, Moose.pm runs
this code:
Moose::Exporter->setup_import_methods(...)
Looking at the setup_import_methods() subroutine in
Moose::Exporter, it goes a few levels deeper but eventually comes up with
anonymous subroutines which it installs in the caller's namespace, that is, in
the Moose namespace, as import() and
unimport().
So now there is an import() subroutine that the
use() code shown above can run.
This still doesn't explain why the strict and
warnings pragmata are turned on for every package that says
use Moose.
If we look at the import() subroutine, we find these two
lines:
strict->import; warnings->import;
Both pragmata, strict and warnings, have
import() subroutines that effectively set a few bits in the magic
variable $^H.
perldoc perlvar has a section on $^H that explains:
This variable contains compile-time hints for the Perl
interpreter. At the end of compilation of a BLOCK the value of this variable is
restored to the value when the interpreter started to compile the BLOCK.
When perl begins to parse any block construct that provides a lexical scope
(e.g., eval body, required file, subroutine body, loop body, or conditional
block), the existing value of $^H is saved, but its value is left unchanged.
When the compilation of the block is completed, it regains the saved value.
Between the points where its value is saved and restored, code that executes
within BEGIN blocks is free to change the value of $^H.
Moose::Exporter explains that calling strict->import;
warnings->import; in a module's import() subroutine works
because these pragmata set $^H, which affects the current
compilation, that is, the file that uses Moose.pm. Therefore Moose doesn't need
to do anything special to make it affect the file that uses Moose rather than
Moose itself, because Moose has already been compiled.
So now we've gotten to the core of things. Let's try our new knowledge in a simple test setup. Let's write a little test program:
#!/usr/bin/env perl use Foo; $x = 1;
Note that we don't turn on strict or warnings, and
we don't declare the variable $x.
Foo.pm looks like this:
package Foo; print "Loading Foo.pm\n"; 1;
When we run the test program, it prints Foo's message, then exits without error.
It doesn't make any difference if we just use the pragmata within Foo.pm:
package Foo; use strict; use warnings; print "Loading Foo.pm\n"; 1;
Running the program of course still doesn't complain that $x is
undeclared.
Now let's do what Moose does and have an import() subroutine
that causes the pragmata to be turned on:
package Foo; use strict; use warnings; sub import { strict->import; warnings->import; } print "Loading Foo.pm\n"; 1;
Now we get the desired effect:
$ perl test.pl Loading Foo.pm Global symbol "$x" requires explicit package name at test.pl line 5. Execution of test.pl aborted due to compilation errors.
Tags: Moose.
posted at: 11:14 | path: /dev | permalink | 0 comments | 0 trackbacks
2008年09月20日
Putting your money where your mouth is
Warning: Rant ahead.
Reacting to the recent meme of "We don't have enough Perl sites", I've started a blog. I've written blog posts every day, sometimes several times per day, but get hardly any visitors. I don't like the idea of link-spamming indiscriminately, so I've only announced new blog posts on use.perl and on Twitter.
Of course, it is entirely possible that the topics I write about are not very interesting. It has been suggested that I should write about things that would cause others to want to link to my blog. Well, I don't have any intentions of sucking up to anybody just to get visitors. I had hoped to write about things I encountered along the way and that I found interesting. I didn't merely want to write about my own modules but also about other sorts of things, especially interesting CPAN modules I've found, or news from the Perl world in Japan and Korea. So I thought of the blog as a community service rather than a wank.
Andy Lester wrote an article in his Perl Buzz blog: Perl must decentralize, diversify and colonize. I agree. Schwern said pretty much the same thing in his "Perl is unDead" talk at YAPC::Asia 2008.
However, saying that there should be more Perl sites is good, but then you should help in driving traffic to those sites as well.
For example - and this is not meant to single out one blogger - Perl Buzz links to the official perl pages, and the official perl pages link to Perl Buzz. I have asked for my blog to be included in planet.perl.org, but didn't even get a response. So the Perl in-crowd link gets all chummy and link to each other and write lots about their own blogs and their own modules, but the small sites are left to fend for themselves.
Put your money where your mouth is.
To be clear, I don't complain about not having thousands of visitors; rather I am disappointed in the nonchalant way in which well-known people who attract lots of visitors from outside the active Perl community proclaim that there must be more Perl sites, but when they do appear, leave them out in the cold.
Nor do I want to single out a specific prolific blogger. I am appealing to all the top Perl bloggers.
Nor do I expect, after having complained about the situation, to have lots of links to my blog suddenly spring up — I am disillusioned to the point where I don't want to continue my blog anymore. Rather, I wanted to highlight a bigger problem.
There are many interesting things happening in the Perl world. Please start writing about them, and start to interact with other Perl blogs.
posted at: 10:33 | path: /misc | permalink | 0 comments | 0 trackbacks
2008年09月18日
Animal references in programming
And of course, there's Moose — though it's not a general programming term.
posted at: 14:25 | path: /misc | permalink | 0 comments | 0 trackbacks
Community Feedback Loop
Most of the high-profile module authors have a lot of modules on CPAN. Which means that generally those modules will be of good quality. A good part of the modules I use day-to-day are from this group of authors.
Generally those perl hackers will also be a part of the community and so you will see them at Perl conferences and on IRC. So one nice side effect from all this is that if you have a question about one of those modules or want to provide a patch you can just get hold of the author on IRC. This is also so much easier if you have already met at a conference.
Knowing a person and the quality of his work also builds trust, so you're more likely to use their code for production.
posted at: 14:23 | path: /misc | permalink | 0 comments | 0 trackbacks
Using attributes for declarative programming
In declarative programming, you specify what to do, but not how to do it.
For example, in an SQL SELECT statement, you tell the database
engine what you want, not how it should lookup the information.
In jQuery as well, you bind events to elements; you don't have to write each basic handler for each element individually.
Perl 5 attributes can also help in making programs more declarative. Take
the :Overload attribute provided by Attribute::Overload. Normally you would use the
overload pragma like this:
package SomeThing; use overload '+' => \&myadd, '-' => \&mysub; sub myadd { ... } sub mysub { ... }
But if the subroutines that implement the overloads are further down in the module, you don't necessarily know that they are overloading an operation. That is because the declaration of which subroutines overloads what is separated from the implementations.
Using the :Overload attribute you can keep things together:
package SomeThing; use Attribute::Overload; sub myadd : Overload(+) { ... } sub mysub : Overload(-) { ... }
So declaring behaviour with attributes can keep definitions where they belong, that is, with the things they modify.
posted at: 14:17 | path: /dev | permalink | 0 comments | 0 trackbacks
The Mind of Damian Conway
O'Reilly has posted an interview video and transcript of The Mind of Damian Conway: Science, Computer Science, the Future of Perl 6, and Advice for Today's Aspiring Programmers. Quote: "[…] to get his thoughts on a wide variety of subjects, including the what-and-when of Perl 6 and what he thinks is important for the next generation of computer scientists".
posted at: 14:12 | path: /misc | permalink | 0 comments | 0 trackbacks
Korean Perl Terms
Korean web sites and slides are, of course, in Korean and written in Hangul. Understanding the Korean language is not so easy, but reading Hangul, the Korean script, is very easy. It is basically an alphabet, based around syllables. Learn to read Hangul with this easy introduction.
Like most languages, Korean uses a lot of loan words for technical concepts. So even if you don't understand Korean, being able to read Hangul will enable you to see certain terms and get an idea what the text is about.
Here is a list of technical terms, Perl-related and otherwise, that you might find interesting. They are sorted according to Hangul sort order. The list is not complete, of course, and additions and corrections are welcome; please tell me on Twitter or mail me at my CPAN email address.
| 다운로드 | download |
| 루비 | ruby |
| 링크 | link |
| 멀티프로세서 | multiprocessor |
| 메일링리스트 | mailing list |
| 모델 | model |
| 모듈 | module |
| 미디어 | media |
| 서브루틴 | subroutine |
| 섹션 | section |
| 스칼라 | scalar |
| 스크립트 | script |
| 스터디 | study |
| 심볼테이블 | symbol table |
| 에디터 | editor |
| 워크샵 | workshop |
| 위키 | wiki |
| 인터넷 | internet |
| 커뮤니티 | community |
| 컴파일러 | compiler |
| 컴퓨터 | computer |
| 크리스마스 | christmas |
| 타입글로브 | typeglob |
| 트랙백 | trackback |
| 파이썬 | python |
| 패키지 | package |
| 펄 | perl |
| 펄매니아 | perlmania |
| 페이지 | page |
| 프로그램 | program |
| 해시 | hash |
| 홈페이지 | homepage |
So have a look at the following Korean Perl-related websites and see if you can pick out one word or the other.
Tags: Asia.
posted at: 12:35 | path: /articles | permalink | 0 comments | 0 trackbacks
Dissecting the Moose Part 1
Jesse Vincent (obra) said on IRC: "Moose looks big and scary, but turns out to be a big kitten. It still has claws, but it mostly is content to sit around in the sun and let you stroke its chin. In return, it looks pretty and entertains you."
But now I want to look inside Moose. Moose is basically a set of layers above Class::MOP. There is the syntactic sugar for the end-user, and a set of custom meta-classes underneath. Moose never creates objects or methods directly; it uses the underlying meta-object protocol to do that. For now, just have a brief look at interacting with Class::MOP:
#!/usr/bin/env perl use warnings; use strict; use Data::Semantic::Net::IPAddress::IPv4; use Class::MOP; use Data::Dumper; my $o = Data::Semantic::Net::IPAddress::IPv4->new; my $meta = Class::MOP::Class->initialize(ref $o); my @parents = $meta->class_precedence_list; warn Data::Dumper->Dump([\@parents, $meta], [qw/*parents meta/]);
So here we create some standard object normally, but then we put the class
under the care of Class::MOP. Now we can introspect the class with MOP methods
like class_precedence_list(), which gives us a list of all parent
classes. We also dump the meta-object itself to see what's going on.
@parents = ( 'Data::Semantic::Net::IPAddress::IPv4', 'Data::Semantic::Net::IPAddress', 'Data::Semantic::Net', 'Data::Semantic', 'Class::Accessor::Complex', 'Class::Accessor', 'Class::Accessor::Installer' ); $meta = bless( { 'namespace' => \undef, 'version' => $meta->{'namespace'}, 'superclasses' => $meta->{'namespace'}, 'method_metaclass' => 'Class::MOP::Method', 'attribute_metaclass' => 'Class::MOP::Attribute', 'package' => 'Data::Semantic::Net::IPAddress::IPv4', 'instance_metaclass' => 'Class::MOP::Instance', 'methods' => {}, 'authority' => $meta->{'namespace'}, 'attributes' => {} }, 'Class::MOP::Class' );
Here we can see that if we ask Class::MOP to create an instance of the class it will use Class::MOP::Instance to do it; if we want to add or inspect an attribute, it will use Class::MOP::Attribute to do it. If we wanted to change the way Class::MOP interacts with our previously standard Perl class, we could tell the meta-object to use different meta-classes.
This was not intended to be a complete tutorial of any sort; I'm just writing down things I'm discovering along the way.
Tags: Moose.
posted at: 10:03 | path: /dev | permalink | 0 comments | 0 trackbacks
2008年09月17日
The Way of Approaching
On Saturday, 21st September and Sunday, 22nd September there will be a Hackathon in Korea at the Cheongju Ramada Hotel. The hackathon's title is The Way of Approaching, and a team of Perl hackers will take part as well, but the focus will be broader than just Perl.
The hackathon is organized by Cho Seong-jae (조성재), who is the Korean Translation Co-Ordinator for KDE and influential in the Korea Free Software movement. He also organizes a meeting of hardcore Linux users every Sunday.
posted at: 20:01 | path: /misc | permalink | 0 comments | 0 trackbacks
Korean Perl Workshop 2008
The Korean Perl Workshop 2008 took place in Seoul on 23rd August; its topic was "Rising Perl". The Korean Perl Mongers are already very active, meeting every week for seven hours to study the language. But this was their first Perl workshop, and I'm very happy to learn that my talk about Perl in Japan and Korea inspired them to do it. Apparently 70 people attended, but they could have had 300 if the venue was big enough.
You can also see the presentations and slides. Of course, most of the slides are in Korean and are written in Hangul, but if you can read Hangul, you will be able to make out certain keywords. Hangul is really easy to learn too — it's just an alphabet, based around syllables.
I've suggested that it might be a nice idea to have another Korean Perl Workshop maybe a week before or after YAPC::Asia 2009. This way you could see Perl events in both Japan and Korea, which to me sounds very interesting and appealing.
Actually, the TwinCity Perl Workshop was advertised as the 100th Perl conference ever, but that was before Philippe Bruhat (BooK), the conference list maintainer, has learned about the Korean Perl Workshop. So now it seems that the Korean Perl Workshop was the 100th Perl conference. I had only mentioned it to BooK because I was not sure whether he was aware of it, but this inadvertently relegated the TwinCity Perl Workshop to 101st place; a fact that will surely not help in making me popular with the TwinCity Perl Workshop organisers…
Tags: Asia, conferences.
posted at: 09:49 | path: /misc | permalink | 0 comments | 0 trackbacks
2008年09月16日
TwinCity Perl Workshop
This is a public service announcement, taken from use.perl.
Vienna.pm has set aside a budget of 1000 Euro to invite speakers to the TwinCity Perl Workshop. If you're not living in Bratislava or Vienna, won't be funded by your company, but want to attend and give a talk, please send e-mail to twincity -at- rt.useperl.at describing why we should invite you and how much it will cost to transport you to Vienna and Bratislava! The deadline for proposals is Sunday 21st September 2008, and we will decide whom to invite until Wed, 24th September.
Of course we're also looking for regular attendees, local speakers and sponsors! :-)
Tags: conferences.
posted at: 10:42 | path: /misc | permalink | 0 comments | 0 trackbacks
The Eskimo Greeting Operator
Perl has a lot of strange and rather unknown operators. At YAPC::Europe 2008, Philippe Bruhat (BooK) gave an interesting talk called Perl (secret) operators.
I'm not sure if the "Eskimo greeting operator" was in there, but it is actually pretty useful. Sometimes when writing a one-liner that involves reading lines of input, you'll want to do something with the resulting data at the end of the loop.
For example, look at a simple one-liner that prompts you for numeric input,
adding each number until you enter just ^D, which produces an
undefined value, thus ending the loop. At the end, it will print the sum of the
values you input.
Normally you'll write something like
perl -lne'$x+=$_; END{print $x}'
What's actually going on here? perldoc perlrun explains how the
-n switch works:
-n causes Perl to assume the following loop around your program,
which makes it iterate over filename arguments somewhat like sed
-n or awk:
LINE:
while (<>) {
... # your program goes here
}
This pseudocode can be taken quite literally. You can use the B::Deparse module to see how perl interprets the one-liner:
perl -MO=Deparse -lne'$x+=$_; END{print $x}'
prints:
BEGIN { $/ = "\n"; $\ = "\n"; } LINE: while (defined($_ = <ARGV>)) { chomp $_; $x += $_; sub END { print $x; } ; }
Since you can't have nested subs, it doesn't matter where you declare the
END block; it will still get run at the end.
But with a little ingenuity you can make this one-liner shorter. Use the
"Eskimo kiss" operator, }{, which might more politically correct
be called the "Inuit kunik" operator, but no one would know what it means.
Basically, if your one-liner contains an outer-level }{, it the
closing brace will terminate the while loop and the opening brace
will start another code block, which will be executed after the loop. In
effect, this creates an END block without the need to explicitly
declare it.
perl -MO=Deparse -lne'$x+=$_}{print $x'
BEGIN { $/ = "\n"; $\ = "\n"; } LINE: while (defined($_ = <ARGV>)) { chomp $_; $x += $_; } { print $x; }
Update: Shawn M Moore (sartak) golfed it to the following:
perl -ple'$x+=$_}{$_=$x'
and even
perl -nle '$;+=$_}{print$'
The latter is particularly evil. Deparse it to see how this works. Exercise for the reader: Combine the last two techniques to make it even shorter.
posted at: 09:28 | path: /dev | permalink | 0 comments | 0 trackbacks
2008年09月15日
Compiling XS Code on AIX
AIX is different. Usually not in a nice way. Getting CPAN modules that use XS code (or any form of C) to compile was sometimes a bit of trial and error, but actually the solution is quite simple — don't use the default cc_r C compiler or even xlC, but use GCC.
In the CPAN shell, do
o conf make_arg "CC=gcc" o conf commit
and watch (most) CPAN modules compile fine.
posted at: 08:27 | path: /misc | permalink | 0 comments | 0 trackbacks
2008年09月14日
Perl V 10.0
Here's an idea to make people more aware of new versions of Perl: Do it like Mac OS X does. After Mac OS 9, there was Mac OS X. And "X" already stands for 10, right? But Apple calls the Operating System "Mac OS X 10.5.4" or similar. Maybe with something as big as an Operating System, people pay attention to third-level changes, so even going from "10.5.3." to "10.5.4." is seen as relevant. But with a "mere" programming language, version jumps in the third level don't get noticed very much. So, to go from "perl 5.8.5." to "perl 5.8.6." was not so big, but people did talk about it when perl went from "perl 5.8.x" to "perl 5.10."
So promote the version levels. Instead of "perl 5.10", call it "Perl V 10.0".
Crazy talk? Maybe. But Tatsuhiko Miyagawa agreed with it and Jesse Vincent suggested something like this separately. So this naming scheme I've discussed may not be such a great idea. But we should do something to get people to take more notice of the evolution of perl (and Perl).
posted at: 09:35 | path: /misc | permalink | 0 comments | 0 trackbacks
2008年09月13日
YAPC::Europe 2008
YAPC::Europe 2008 has been over for a while, and quite a few people have written about it and posted pictures, slides and videos. So I won't reiterate all that information here but will write about subjective impressions.
I liked the conference a lot; the selection of talks was interesting and the venue was excellent. The conference dinner was good as well, but as a suggestion — if you're going to have a buffet, please don't make it a sit-down dinner. The idea of "this row goes first, that row goes last" just doesn't work. Having said that, there was enough food for everyone, and it was good. YAPC::Asia 2008 did it well; there were big tables with food and drinks and people just wandered around, socialized and took whatever they wanted from the buffet - there was no queue.
If you're ever in Copenhagen, avoid the Cabinn Hotels. Their motto is "Sleep Cheap in Luxury", but it's a lie — the only true word is "in". It was not cheap (I've stayed in a much better hotel in Tokyo for two-thirds the price), it certainly was not luxurious, and as for sleep — well, the bed wasn't comfortable either. I've realized that when I'm going to Perl conferences, I want to have a good time and get motivation, and there aren't that many conferences I'll go to, so in the future I'll choose nice hotels.
The other thing I'd like to comment on is the auction. Please make it faster next time — see how Greg (McCarroll) does it. And leave out the stripping, wrestling and other "laddish" things — are you still wondering why there are so few women in the Perl community?
But all this nagging shouldn't detract from the fact that I've thoroughly enjoyed myself; it was good to meet all the people again, to get fresh ideas, and to get a feeling of belonging within the Perl community. Congratulations and thanks to the organizers.
I've uploaded some photos from Copenhagen and the YAPC.
Tags: conferences, YAPC.
posted at: 21:53 | path: /misc | permalink | 0 comments | 0 trackbacks
Error - Day too big
Generally, my days aren't too big — they're too small (or rather, too short).
$ perl -MTime::Local -e 'timelocal(0,0,0,1,1,2038-1900)' Day too big - 24868 > 24853 Cannot handle date (0, 0, 0, 1, 1, 2038) at -e line 1
That's a Time::Local error, but there is an underlying symptom.
Schwern got a grant from the TPF to fix it.Prevent the Y2038 bug from effecting Perl users. This means make localtime() and gmtime() work for times beyond 2038. Do this regardless of the state of the system C libraries.
A working solution, in C, already exists. This grant is to finish the portability issues, write additional tests and change perl to use the repaired C library.
Schwern seems to have been successful with it because he tweeted:
$ perl -wle 'print scalar localtime(2**33 + 60*60*24*365*16)' Fri Mar 12 04:56:32 2258
Update: Schwern told me that you can find the patched version of Perl on Google Code.
posted at: 10:19 | path: /misc | permalink | 0 comments | 0 trackbacks
2008年09月12日
Repeating Elements in an Array Slice
This is a neat possibility in Perl that I hadn't realized before: By mentioning element indices in an array slice repeatedly, you get a list with multiple copies of that element.
for (("to you", 'miyagawa')[0,0,1,0]) { print "Happy birthday $_\n" }
You can run it in codepad, and it prints:
Happy birthday to you Happy birthday to you Happy birthday miyagawa Happy birthday to you
And bychance it is Tatsuhiko Miyagawa's 31st birthday today, so it is oddly appropriate.
posted at: 17:25 | path: /dev | permalink | 0 comments | 0 trackbacks
Acme::CPANAuthors::Austrian
I wrote and released Acme::CPANAuthors::Austrian which is sort of a plugin to Acme::CPANAuthors by Kenichi Ishigaki (charsbar). That idea is that you provide a list of CPAN authors that are in the same group, for example, because they live in the same country, or they use the same repository (e.g., CodeRepos). Acme::CPANAuthors can then give you statistics and more information, such as the number of authors, their IDs, a list of their distributions, their avatar URLs, CPANTS data on the kwalitee of their distributions etc.
So far there have been plugins for Japan, China, Brazil and CodeRepos. Sébastien Aperghis (maddingue) is working on a French version.
Here's the list of the thirteen Austrian CPAN authors I've got so far.
- ANDK (Andreas J. König)
- AREIBENS (Alfred Reibenschuh)
- DOMM (Thomas Klausner)
- DRRHO (Robert Barta)
- FLORIAN (Florian Helmberger)
- GARGAMEL (Karlheinz Zöchling)
- LAMMEL (Roland Lammel)
- MARCEL (Marcel Gruenauer == hanekomu)
- MAROS (Maroš Kollár)
- NINE (Stefan Seifert)
- PEPL (Michael Kröll)
- RGIERSIG (Roland Giersig)
- ZEYA (Hansjörg Pehofer)
posted at: 17:03 | path: /dev | permalink | 0 comments | 0 trackbacks
CPAN Gems: Proc::InvokeEditor
This is the first in a series of posts where I will show you CPAN modules I've stumbled across. If I find an interesting and well-documented module, I'll post the relevant part of the manpage.
Today, please take a look at Proc::InvokeEditor by Michael Stevens.
Proc::InvokeEditor - Perl extension for starting a text editor
use Proc::InvokeEditor; my $edited_text = Proc::InvokeEditor->edit($unedited_text);
This module provides the ability to supply some text to an external text editor, have it edited by the user, and retrieve the results.
The File::Temp module is used to provide secure, safe temporary files, and File::Temp is set to its highest available level of security. This may cause problems on some systems where no secure temporary directory is available.
When the editor is started, no subshell is used. Your path will be scanned to find the binary to use for each editor if the string given does not exist as a file, and if a named editor contains whitespace, e.g. if you try to use the editor "xemacs -nw", then the string will be split on whitespace and anything after the editor name will be passed as arguments to your editor. A shell is not used but this should cover most simple cases.
posted at: 09:11 | path: /cpan_gems | permalink | 0 comments | 0 trackbacks
2008年09月11日
Overloading Constants in Perl
How would you like to change the value of 4? Do you like 2 + 2 to be 5? In Perl, you can use the "overload" pragma to overload constants.
use overload; BEGIN { overload::constant integer => sub { $_[1] * 2 } } my $x = 4; print "x = $x\n"'
This should print "x = 8". Run it in codepad.
The documentation of overload.pm says:
Overloading constants
For some applications, the Perl parser mangles constants too much. It is
possible to hook into this process via "overload::constant()" and
"overload::remove_constant()" functions.
These functions take a hash as an argument. The recognized keys of this hash
are:
integer to overload integer constants,
float to overload floating point constants,
binary to overload octal and hexadecimal constants,
q to overload "q"-quoted strings, constant pieces of "qq"- and
"qx"-quoted strings and here-documents,
qr to overload constant pieces of regular expressions.
The corresponding values are references to functions which take three
arguments: the first one is the initial string form of the constant, the second
one is how Perl interprets this constant, the third one is how the constant is
used. Note that the initial string form does not contain string delimiters,
and has backslashes in backslash-delimiter combinations stripped (thus the
value of delimiter is not relevant for processing of this string). The return
value of this function is how this constant is going to be interpreted by Perl.
The third argument is undefined unless for overloaded "q"- and "qr"- constants,
it is "q" in single-quote context (comes from strings, regular expressions, and
single-quote HERE documents), it is "tr" for arguments of "tr"/"y" operators,
it is "s" for right-hand side of "s"-operator, and it is "qq" otherwise.
With this in mind I wrote Scalar::Properties a few years ago.
use Scalar::Properties; my $val = 0->true; if ($val && $val == 0) { print "yup, its true alright...\n"; } my @text = ( 'hello world'->greeting(1), 'forget it', 'hi there'->greeting(1), ); print grep { $_->is_greeting } @text; my $l = 'hello world'->length;
Scalar::Properties attempts to make Perl more object-oriented by taking an idea from Ruby: Everything you manipulate is an object, and the results of those manipulations are objects themselves.
Constants are turned into objects so we can call methods on them. And that class overloads stringification and so on so when these constants are used, they behave normally.
autobox does something similar, but does it with XS.
posted at: 16:09 | path: /dev | permalink | 0 comments | 0 trackbacks
