develooper Front page | perl.perl6.language | Postings from September 2001

Re: Custom iterators

Thread Previous | Thread Next
From:
Michael G Schwern
Date:
September 25, 2001 09:42
Subject:
Re: Custom iterators
Message ID:
20010925124243.E620@blackrider
On Tue, Sep 25, 2001 at 08:39:06AM +0100, Piers Cawley wrote:
> Michael G Schwern <schwern@pobox.com> writes:
> [ A description of the Ruby 'block' syntax ]
> 
> Note too that, adopting the block syntax would let you do:
> 
>     File.new($filename) { ... }
> 
> Which doesn't look like much, but new could be implemented in such a
> way that, if called with a block, the constructor would simply iterate
> over the file and then explicitly close the file. Given the GC issues
> of immediate finalization being hard to do (albeit possible), using
> constructs that don't need it would surely be a Good Thing.

Other fun things I was thinking of overnight...

Instead of:

    open(FILE, $file) || die "Couldn't open $file:  $!";
    while( read(FILE, my $buf, $length) ) {
        print $buf;
    }
    close FILE;

you can do

    File.read($filename, $length) {
        print
    }

implemented like so:

    sub File::read {
        my($filename, $length, $offset) = @_;

        use POSIX qw(BUFSIZ);
        $length ||= BUFSIZ;

        $offset ||= 0;

        open(my $fh, $filename) || die "Can't open $filename:  $!";
        while(read($fh, $_, $length, $offset)) {
            yield;
        }
        close $fh;
    }

Or how about character by character?

    File.each_byte($filename) {
        print
    }

Backwards?

    File.read_backwards($filename) {
        print
    }

How about each line seperated by the string "Peterbilt"?

    my $fh = File.open($filename);
    $fh.each('Peterbilt') {
        print
    }

Tasty.


-- 

Michael G. Schwern   <schwern@pobox.com>    http://www.pobox.com/~schwern/
Perl6 Quality Assurance     <perl-qa@perl.org>	     Kwalitee Is Job One
...and I pull out the Magnum from under the desk where I keep it in case
someone laughs at a joke that's so dry it's got a built in
water-fountain, and blow the lot of them away as a community Service.
	-- BOFH

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About