Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: Insert row from file

by Gilimanjaro (Hermit)
on Dec 31, 2004 at 11:16 UTC ( #418511=note: print w/replies, xml ) Need Help??

in reply to Insert row from file

Untested code below, but I think it should do the trick...
# First build a hash we can use to look up lines (keyed on 2nd line) my %pairs; open A, "<A"; while(<A>) { $pairs{<A>}=$_ } close A; # We use a third file open C, ">C"; open B, "<B"; while(<B>) { # If this line matches a known 2nd line, insert it's 1st print C $pairs{$_} if exists $pairs{$_}; # Always print the original line print C $_; } close B; close C;

Replies are listed 'Best First'.
Re^2: Insert row from file
by Hena (Friar) on Dec 31, 2004 at 12:04 UTC
    Also to add to Gilimanjaro's post, easy way to overwrite the original is by using rename.
    rename (C,B);
    Although when overwriting old files, be sure you are doing the right thing as returning to old might prove difficult. This depends on where the original file came from of course.
Re^2: Insert row from file
by smbs (Acolyte) on Dec 31, 2004 at 15:32 UTC
    Thanx work just great
Re^2: Insert row from file
by smbs (Acolyte) on Dec 31, 2004 at 22:52 UTC
    If u have the patience --can u explain how it works!!!
Re^2: Insert row from file
by smbs (Acolyte) on Jan 06, 2005 at 20:38 UTC
    At last I more or less understand it --but you mentioned in first line comment "(keyed on 2nd line)" --how is this done -the file was read in and every 2nd line is the key --is this some sort of default-what if I wanted every odd line (lines 1,3,5 etc) to be the keys??

      It works because of the way the while loop works: The conditional in the while loop always gets evaluated first, before the content of the loop block. The <A> operator, when used in a while conditional, assigns the line gotten from file A to $_, starting with the 1st line.

      The body of the loop, again uses the <A> operator, which gets the next line; you can access a line only once using the <> operator. I use it directly as the key to the %pairs hash, so the key is the 2nd line. It assigns the value of $_ (which was set in the while conditional) to this element of %pairs.

      The loop evaluates the conditional again, gets the 3rd line, and assigns it to $_, and the body does the same all over again with the fourth line. So the even/odd mechanism is caused by the double use of <A>.

      If I wanted to key on the odd lines, I'd've used $pairs{$_}=<A>;

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://418511]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2022-08-15 13:45 GMT
Find Nodes?
    Voting Booth?

    No recent polls found