in reply to file reading issues

There are a couple ways I can think of to do that, offhand. If it's a small file and you can read it all into memory, you can do something like this:
my $file = '/path/to/file.txt'; open(IN,"<$file") || die $!; read IN, my $html, -s $file; close(IN); $html =~ s/<!-- Begin -->(.*?)<!-- End -->/$1/s;

Or, if the file is large and you'd like to read it line by line, you might want to try setting a flag when Begin is encountered, then turning it off again when End is hit.
my $flag = 0; while (<FILE>) { $flag = 1 if (/<!-- Begin -->/); $flag = 0 if (/<!-- End -->/); process_line($_) if ($flag); }

Replies are listed 'Best First'.
Re^2: file reading issues
by JediWizard (Deacon) on Aug 03, 2005 at 19:19 UTC

    I notice you have a different method for reading an entire file into memory then I am used to seeing. I was wondering if there is any reason you are aware of that makes your way better or worse than the way I use (or if they are just different (TIMTOWTDI)). If there is, I'd love to hear about it.

    read IN, my $html, -s $file; # your code my $file = do{ local $/; <IN> }; # The way I usually use.

    Other monks... can anybody tell me if there is an advantage in one way or the other?

    Update The secode line of cone above is the way I am used to seeing... I forgot to complete the comment. My question regards the difference between using $/ as opposed to using read to slurp in an entire file.


    They say that time changes things, but you actually have to change them yourself.

    —Andy Warhol

      What is the way you're used to seeing? Maybe I am the one in need of enlightenment and your way is superior.

      To answer your question, there is no reason why I do it that way except that's the way I learned how to do it. Maybe there was a good reason to do it like that back then which has now been made moot by advances in Perl - I don't know.

        Sorry... apparently I forgot to type part of my question... Allow me to update.


        They say that time changes things, but you actually have to change them yourself.

        —Andy Warhol

      IMO, the difference will be what kind of buffered I/O gets performed. Fuller explanation: Re: Speed reading (files)

      One world, one people