http://www.perlmonks.org?node_id=196040


in reply to Basic Seek

If I understand this correctly...
# open the input file open(IN,"file") or die; # # open a temporary output file ( you could also use the # -i "inplace edit feature", see perldoc perlrun ) # open(OUT,">file.$$") or die; # # print the contents of IN to OUT, # adding your additional line if we # see $dom as the first chars of the line # \Q and \E to quotemeta the domain since # it probably contains metachars like "." # while (<IN>) { print OUT; if (/^\Q$dom\E\s/) { print OUT "$user\@$dom\t$user\n"; } } # close both files and overwrite # IN with OUT via rename(). close IN; close OUT; rename("file.$$","file") or die;

Update: Regarding the reply...other than the fact that it's opening a file called "file", the above is doing what you are asking. I think perhaps you are focused on the word seek. The seek() operator doesn't look for strings, it's given a byte offset and moves the file pointer.

Also, you seem fixated on editing the file in place. This isn't really possible in your situation. Perl can make it appear that way with it's "-i" feature. See perlrun.

Replies are listed 'Best First'.
Re: Re: Basic Seek
by lostperls (Initiate) on Sep 08, 2002 at 16:45 UTC
    my original code (before i changed the layout of the file) looked like this:
    my $datafile = '/etc/postfix/virtual'; my $req_addr = "$username\@$domain"; my ( $name, $atdomain ) = $req_addr =~ /^([\w.-]+)(@[\w.-]+)$/ ; open FH, $datafile or die; my @virtual = <FH> ; close FH ; open FH, ">$datafile" or die; my $wrote_it = 0 ; for ( @virtual ) { print FH $_ ; if ( $_ =~ /$atdomain/ && !$wrote_it ) { print FH "$req_addr\t$username\n" ; $wrote_it++ ; } } close FH ;
    Which would edit the /etc/postfix/virtual file if it looked like this:
    aaaa.com VIRTUALDOMAIN @aaaa.com postmaster bbbb.com VIRTUALDOMAIN @bbbb.com postmaster cccc.com VIRTUALDOMAIN @cccc.com postmaster

      I've seen that exact same code before (apart from the two lines that now have $atdomain instead of $domain), with the same question.

      I mumbled something about Tie::File. That might still be a nice solution.

      — Arien

Re: Re: Basic Seek
by Anonymous Monk on Sep 08, 2002 at 16:19 UTC
    judging by what you have there, i don't think that i explained it correctly.
    I need the script to do the following:

    1. open /etc/postfix/virtual (which is arranged as above)
    2. seek to the line that begins with the same value as $dom
    3. do a return at the end of that line and print $user\@$dom\t$user

    Hope this is clearer. (i'm crap at explaining).
    Thanks
Re: Re: Basic Seek
by Anonymous Monk on Sep 08, 2002 at 16:27 UTC
    so if $user is bob and $dom is aaaa.com, the file will look like below once it has been wrote to:
    aaaa.com VIRTUALDOMAIN bob@aaaa.com bob bbbb.com VIRTUALDOMAIN cccc.com VIRTUALDOMAIN dddd.net VIRTUALDOMAIN
    Thanks