Loading ...
Sorry, an error occurred while loading the content.

Re: [PBML] Look ahead in a file?

Expand Messages
  • Jeff 'japhy' Pinyan
    ... Well, you can store your current location $here_i_am = tell FILE; do some stuff while ( ) { ... } and then restore your position: seek FILE,
    Message 1 of 3 , Feb 3, 2004
    • 0 Attachment
      On Feb 3, Electron One said:

      >Is there a way to look ahead in a file?

      Well, you can store your current location

      $here_i_am = tell FILE;

      do some stuff

      while (<FILE>) { ... }

      and then restore your position:

      seek FILE, $here_i_am, 0;

      I suggest reading 'perldoc -f seek' and 'perldoc -f tell' for more.

      --
      Jeff "japhy" Pinyan japhy@... http://www.pobox.com/~japhy/
      RPI Acacia brother #734 http://www.perlmonks.org/ http://www.cpan.org/
      <stu> what does y/// stand for? <tenderpuss> why, yansliterate of course.
      [ I'm looking for programming work. If you like my work, let me know. ]
    • daymobrew@yahoo.com
      ... http://www.cpan.org/ ... course. ... know. ] Another option could be to read the entire file into memory, if it s not too big. open( FH, filename.ext );
      Message 2 of 3 , Feb 4, 2004
      • 0 Attachment
        --- In perl-beginner@yahoogroups.com, Jeff 'japhy' Pinyan <japhy@p...>
        wrote:
        > On Feb 3, Electron One said:
        >
        > >Is there a way to look ahead in a file?
        >
        > Well, you can store your current location
        >
        > $here_i_am = tell FILE;
        >
        > do some stuff
        >
        > while (<FILE>) { ... }
        >
        > and then restore your position:
        >
        > seek FILE, $here_i_am, 0;
        >
        > I suggest reading 'perldoc -f seek' and 'perldoc -f tell' for more.
        >
        > --
        > Jeff "japhy" Pinyan japhy@p... http://www.pobox.com/~japhy/
        > RPI Acacia brother #734 http://www.perlmonks.org/
        http://www.cpan.org/
        > <stu> what does y/// stand for? <tenderpuss> why, yansliterate of
        course.
        > [ I'm looking for programming work. If you like my work, let me
        know. ]

        Another option could be to read the entire file into memory, if it's
        not too big.

        open( FH, "filename.ext" ); # Omit 'die' for readability.
        my @Wholefile = <FH>;
        close( FH );

        Now each line is in a different entry of @Wholefile i.e. $Wholefile[0]
        is the first line of the file and $Wholefile[$#Wholefile] is the last
        line.
        This makes it easy to look ahead.
        You can make changes to @Wholefile and then write it back to disk when
        you are finished.
      Your message has been successfully submitted and would be delivered to recipients shortly.