On 27/01/2011 06:23, Ramesh Kumar wrote:
Hi Rob, I refer to your 2 lines of code: my $data = '<{5, 26}{20, 42, 64}{23, 48}>'; my $list = [ map { [ $_ =~ /\d+/g ] } $data =~ /(\{.*?\})/g ]; That's the type of Perl coding style I'm still trying to learn. Concise and elegant. Beautiful!!!
Code like that can be useful as an exercise as it tests your understanding of Perl constructs quite well. But I would never recommend that you write like that on a regular basis as it takes a /long/ time for someone else to comprehend if they have to maintain your code. You would even kick yourself for being so clever if you had to come back to some of your own code at a later date and couldn't see its structure at a glance. That is why I wrote code that works using a loop but achieves the same result in a similar way. It is worth pointing out that the one-liner is also inefficient with memory, as the list generated by $data =~ /(\{.*?\})/g is created all at once and then mapped, whereas the loop creates and processes a single bracketed sublist at a time. It is also likely to be slower, although I haven't benchmarked it. Always write something that explains what it does and so needs minimum commenting!
I am having a tough time to crack the secret of Perl's contexts. Any websites/books you could recommend which covers this area in depth and clearly?
I think the section (2.7) on context in Programming Perl is clear and helpful. And have you seen the tutorial on Perl Monks? <http://www.perlmonks.org/?node_id=738558> I also recommend playing with a subroutine that displays its called context, like the program below. It lets you see the contexts that different calls apply. use strict; use warnings; sub context { my $list_context = wantarray(); if (not defined $list_context) { print "Void context\n"; } elsif ($list_context) { print "List context\n"; } else { print "Scalar context\n"; } } no warnings 'void'; # Don't warn about void calls [ context() ]; context() & 1; ( context() ); **OUTPUT** List context Scalar context Void context -- To unsubscribe, e-mail: beginners-unsubscr...@perl.org For additional commands, e-mail: beginners-h...@perl.org http://learn.perl.org/