CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
Specific lines from external file?

 



zicero
Deleted

Sep 20, 2000, 12:35 PM

Post #1 of 3 (1212 views)
Specific lines from external file? Can't Post

Is there a way I can get to read/write to a specific line
in an external file.

Say, I open a file:
- - - - - - - - - -
open(FILE, ">> $variable") | | die("Yea...\n");
# inhales the content:
@data = <FILE>;
# closes the file again
close(FILE);
- - - - - - - - - -

Then I can use "foreach" to get the list to a variable,
but if I want to read e.g. from line 3,
and then write to line 3 in my external file,
how can I do that?

I'm just starting out, please be nice to me Smile

Mick

------------------
http://www.zicero.dk


Kanji
User / Moderator

Sep 21, 2000, 7:25 PM

Post #2 of 3 (1212 views)
Re: Specific lines from external file? [In reply to] Can't Post

Personally, I use while to read file as its usually more efficient than foreach and you get to use nifty things like $. which tells you what line you're on.

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

my $line_no = 13;
my $line;
open FILE, $file or die "Can't open $file: $!";
while ( <FILE> ) {
# If we've already got our line,
# there's no point in continuing
# reading the rest of the file.
last if $. > $line_no;


# If this isn't the line we want
# skip to the next.
next if $. != $line_no;


# Hey, we're made it to the line we
# wanted ... let's save it to $line.
$line = $_;
}</pre><HR></BLOCKQUOTE>

If you insist on reading the entire file into an array though, you can read the line you want by accessing $array[X] where X is the line number minus 1 (ie, 0 for line 1, 1 for line 2, etc.).

Writing is pretty much the same, but you need to either read in the file and then re-open it for writing, or write to a temporary file and switch them.

Alternately, you can use in place edits ( -i or $^I ) and the magic of <>.

<BLOCKQUOTE><font size="1" face="Arial,Helvetica,sans serif">code:</font><HR>

{
local( $^I, @ARGV ) = ( ".bak", $variable );
while ( <> ) {
last if $. > $line_no;
next if $. != $line_no;
s/this/that/; # Change this to that.
}
}</pre><HR></BLOCKQUOTE>

Poke around the docs for more on in-place edits.


zicero
Deleted

Sep 22, 2000, 1:27 AM

Post #3 of 3 (1212 views)
Re: Specific lines from external file? [In reply to] Can't Post

I will try using while then.
Still very new to this PERL language stuff,
but it seems cool so I want to learn it.

Thanks for your help.

Mick

------------------
http://www.zicero.dk

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives