help on Schwartzian method
am 12.06.2007 18:29:43 von jis
Hi all,
I was reading through UR coloumn by Randal in ww.stonehenge.com. I
cam across the Schwartzian method which I find extremely difficult to
understand even after the explanation given by him.Please help me
understand the concepts.
1)
@data = <>; # read data
foreach (@data) {
($name,$score) = split; # get score
$score{$_} = $score; # record it
}
I guess $_ has the instantaneous data from @data. Am I correct?
2)
@pairs = map {
($name, $score) = split;
[ $_, $score ];
} @data;
What is $_ in the ablove code?
Randal says "I build a two-element anonymous list from the
$score and the original value $_". Can somebody help me to understand
what he means?
3)
print
map { $_->[0] }
sort { $a->[1] <=> $b->[1] }
map { [$_, (split)[1] ] }
<>;
What is $_->[0] all about?
regards,
jis
Re: help on Schwartzian method
am 12.06.2007 21:26:17 von Jim Gibson
In article <1181665783.587223.115180@a26g2000pre.googlegroups.com>, jis
wrote:
> Hi all,
>
> I was reading through UR coloumn by Randal in ww.stonehenge.com. I
> cam across the Schwartzian method which I find extremely difficult to
> understand even after the explanation given by him.Please help me
> understand the concepts.
>
> 1)
> @data = <>; # read data
> foreach (@data) {
> ($name,$score) = split; # get score
> $score{$_} = $score; # record it
> }
>
> I guess $_ has the instantaneous data from @data. Am I correct?
Yes. $_ is the default variable for many Perl operations if an explicit
variable is not present.
>
> 2)
>
> @pairs = map {
> ($name, $score) = split;
> [ $_, $score ];
> } @data;
> What is $_ in the ablove code?
$_ is aliased to each element of @data in turn within the block of the
map statement.
> Randal says "I build a two-element anonymous list from the
> $score and the original value $_". Can somebody help me to understand
> what he means?
The construct [ $_, $score ] creates a list of two elements and returns
a reference to that list. The list is "anonymous" because it is not
assigned to a named variable, e.g. such as the variable @list in "my
@list = ($_,$score);". There will be one such list for each element of
@data. The references to all of these anonymous lists will be stored in
the array @pairs.
>
>
> 3)
> print
> map { $_->[0] }
> sort { $a->[1] <=> $b->[1] }
> map { [$_, (split)[1] ] }
> <>;
> What is $_->[0] all about?
$_ is a scalar variable that contains a reference to a list. $_->[0] is
the first element of that list. It is equivalent to ${$_}[0], but
perhaps a little more readable.
Posted Via Usenet.com Premium Usenet Newsgroup Services
----------------------------------------------------------
** SPEED ** RETENTION ** COMPLETION ** ANONYMITY **
----------------------------------------------------------
http://www.usenet.com