Johannes Eriksson wrote:
> 
> * Bret Hughes [Mon, Feb 19, 2001 at 12:39:22AM -0600]:
> >  i believe you. I just can't figure out what it is doing?  I have been
> > working with perl lately and always looking to learn.  Can you explain
> > what it is doing please?

> Here's the same script in a less compact but easier-to-understand
> form:
> 
> 01    #!/usr/bin/perl
> 02
> 03    srand;
> 04    while (<>)
> 05    {
> 06      if (rand($.) < 1)
> 07        {
> 08          $line = $_;
> 09        }
> 10    }
> 11    print $line;
> 
> As you can see, I've rewritten the '(EXPR1) while (EXPR2)' statement
> into a more readable 'while (EXPR) BLOCK' (line 4), and the
> '(EXPR1) && (EXPR2)' statement into an 'if (EXPR) BLOCK'. Otherwise
> it's pretty much the same.
> 
> For each loop iteration, a new input line is read and stored into
> the $_ variable (this is what <> does). Line 6 is where the magic
> occurs: $. holds the current line number (starting from 1, call it N),
> so the call to rand will always produce a random fractional number in
> the range 0..N. As you can see, the probability of selecting a line is
> always 1/lines_read and thus the final probability for each line becomes
> 1/N.
> 
> The selected line is then printed on line 11.


Thanks that helps alot.I now understand the implied if using the logical
"and" and it becomes clear.  I also see that $_ may get written over
several times as the loop cruises along but only the last case where
rand returns < 1 will be used.  It seems that this would more tend to
return the earlier lines in the file rather than the later since it does
not actually use the number chosen as $. = the last line, but will
select it only if on the last iteration rand happens to return <1.

I appreciate your time and do see how once the construct is understood
it can be used easily.

Thanks again,

Bret



_______________________________________________
Redhat-list mailing list
[EMAIL PROTECTED]
https://listman.redhat.com/mailman/listinfo/redhat-list

Reply via email to