It is possible to make a single Perl program file that contains multiple input files for reading. I show an example below. In your case, there are 3 input files and the output goes to STDOUT. Anybody can download my single .pl file and run it and see what it does.
You seem to be having trouble dealing with files in general. How to open a file handle, etc. The Monks have given you some great pointers on that. This is a basic thing that you need to know how to do in any programming language.
I work with beginners in a number of programming languages at a local college. The first and most important file skill (besides how to open and close files) is to process input files one line at a time. When you create an array of the entire file in memory (slurp, etc) and then process that array, you are actually reading each data line twice and consuming memory in the process. This is usually not necessary or desired.
Your desired code does seem a bit contrived to me. Is this a homework assignment? I would not have written an assignment like this. Having 2 files where line 3 of one matches up with line 3 of the other is pretty rare. That is because this is a very error prone format - there is a lot that can go wrong! But yes, these things do exist.
Below I check for "defined" when reading a line from the inline file. That is because EOF (End of File) for an inline file is detected a bit differently than when reading an actual file. This extra (is defined?) step works fine with real files, but isn't necessary.
Update:#!/usr/bin/perl use strict; use warnings; use Inline::Files; # allows files to be included in source code my $template = <TEMPLATE>; # reads first line # $template has a trailing \n my $name; while (defined ($name = <NAME>) and $name =~ /\S+/) # process until bl +ank line { chomp $name; my $ip; defined ($ip = <IP>) and $ip =~ /\S+/ or die "Mis-matched number o +f lines"; chomp $ip; printf ($template,$name,$ip); # note uses the \n within template +line } =prints: my name is john. My local machine ip is 10.0.1.2. my name is peter. My local machine ip is 10.2.3.4. my name is mickey. My local machine ip is 10.3.4.5. =cut __TEMPLATE__ my name is %s. My local machine ip is %s. __NAME__ john peter mickey __IP__ 10.0.1.2 10.2.3.4 10.3.4.5
In reply to Re: Need to replace string from external file
by Marshall
in thread Need to replace string from external file
by bhupi70007
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |