Perl: Couldn't open a file with file name as input - perl

I am trying to copy lines of a file to another file.I want to give filenames for both input and output file. I tried to do without asking for any input parameters and it worked fine but with filename as input it failed.Here is my code:
use strict;
use warnings;
#names of file to be input and output
my $inputfile = <STDIN>;
my $outputfile = <STDIN>;
open(INPUT,'<', $inputfile)
or die "Could not open file '$inputfile' $!";
open(OUTPUT, '>', $outputfile)
or die "Could not open file '$outputfile' $!";
while (<INPUT>) {
print OUTPUT;
}
close INPUT;
close OUTPUT;
print "done\n";

chomp your input variables to remove the newlines:
use strict;
use warnings;
#names of file to be input and output
my $inputfile = <STDIN>;
my $outputfile = <STDIN>;
chomp $inputfile;
chomp $outputfile;
open(INPUT,'<', $inputfile)
or die "Could not open file '$inputfile' $!";
open(OUTPUT, '>', $outputfile)
or die "Could not open file '$outputfile' $!";
while (<INPUT>) {
print OUTPUT;
}
close INPUT;
close OUTPUT;
print "done\n";

Related

Printing a content of a file to the screen in perl

I Have a perl script which write a few lines into file. (I checked and see that the file is written correctly)
right after that I want to print the content to the screen, the way I'm trying to do it- is to read the file and print it
open (FILE, '>', "tmpLogFile.txt") or die "could not open the log file\n";
$aaa = <FILE>;
close (FILE);
print $aaa;
but I get nothing on the screen, what do I do wrong?
To read you need to specify the open mode as <.
Also, $aaa = <FILE> has scalar context, and only reads a line.
Using print <FILE> you can have list context and read all lines:
open (FILE, '<', "tmpLogFile.txt") or die "could not open the log file\n";
print <FILE>;
close (FILE);
try this:
use strict;
use warnings;
my $filename = 'data.txt';
open(my $fh, '<:encoding(UTF-8)', $filename)
or die "Could not open file '$filename' $!";
while (my $row = <$fh>) {
chomp $row;
print "$row\n";
}
print "done\n"

Add a string at the beginning of the file with OPEN CLOSE function in Perl

My code did not work for my any modifications. other than append nothing works for in open close functions.
#!/usr/local/bin/perl
my $file = 'test';
open(INFO, $file);
print INFO "Add this line please\n";
print INFO "First line\n";
close(INFO);
You need to tell perl what type of filehandle you want
open(INFO, ">", "$file")|| die "Cannot open $file";
This will create and write to a file.
Look up
http://perldoc.perl.org/functions/open.html
By default open(INFO, $file) will take the file handle in read mode('<') . So until unless you specify the write mode('>') you cannot print the values into the file . When you write the code you should use : use strict; and use warnings; which will be helpful.
Code:
use strict;
use warnings;
my $InputFile = $ARGV[0];
open(FH,'<',"$InputFile")or die "Couldn't open the file $InputFile: $!";
my #file_content = <FH>;
close(FH);
open(FH,'>',"$InputFile") or die "Cannot open $InputFile: $!";
#String to be added at the begining of the file
my $file = "test";
print FH $file . "\n";
print FH #file_content;
close(FH);

To replace a string and append a string in perl in 1 file

I want to replace a line in my file and after replacing it I want to append another line. As you can see here, I have to open and close files for 2 times. Can I do it by opening a file only once? Thanks
use strict;
use warnings;
open(FILE,"tmp1.txt") || die "Can't open file: $!";
undef $/;
my $file = <FILE>;
my #lines = <FILE>;
my #newlines;
for each(#lines) {
$_ =~ s/hello/hi/g;
push(#newlines,$_);
}
close(FILE);
open(FILE, "> tmp1.txt ") || die "File not found";
print FILE #newlines;
close(FILE);
open(FILE,"tmp1.txt") || die "Can't open file: $!";
undef $/;
my $file = <FILE>;
my #lines = <FILE>;
my $first_line = "hi";
my $second_line = "sun";
my $insert = "good morning";
$file =~ s/\Q$first_line\E\n\Q$second_line\E/$first_line\n$insert\n$second_line/;
open(OUTPUT,"> tmp3.txt") || die "Can't open file: $!";
print OUTPUT $file;
close(OUTPUT);
Use Three-arg open and open your file in Read+Write mode by +<.

copy text after a specific string from a file and append to another in perl

I want to extract the desired information from a file and append it into another. the first file consists of some lines as the header without a specific pattern and just ends with the "END OF HEADER" string. I wrote the following code for find the matching line for end of the header:
$find = "END OF HEADER";
open FILEHANDLE, $filename_path;
while (<FILEHANDLE>) {
my $line = $_;
if ($line =~ /$find/) {
#??? what shall I do here???
}
}
, but I don't know how can I get the rest of the file and append it to the other file.
Thank you for any help
I guess if the content of the file isn't enormous you can just load the whole file in a scalar and just split it with the "END OF HEADER" then print the output of the right side of the split in the new file (appending)
open READHANDLE, 'readfile.txt' or die $!;
my $content = do { local $/; <READHANDLE> };
close READHANDLE;
my (undef,$restcontent) = split(/END OF HEADER/,$content);
open WRITEHANDLE, '>>writefile.txt' or die $!;
print WRITEHANDLE $restcontent;
close WRITEHANDLE;
This code will take the filenames from the command line, print all files up to END OF HEADER from the first file, followed by all lines from the second file. Note that the output is sent to STDOUT so you will have to redirect the output, like this:
perl program.pl headfile.txt mainfile.txt > newfile.txt
Update Now modified to print all of the first file after the line END OF HEADER followed by all of the second file
use strict;
use warnings;
my ($header_file, $main_file) = #ARGV;
open my $fh, '<', $header_file or die $!;
my $print;
while (<$fh>) {
print if $print;
$print ||= /END OF HEADER/;
}
open $fh, '<', $main_file or die $!;
print while <$fh>;
use strict;
use warnings;
use File::Slurp;
my #lines = read_file('readfile.txt');
while ( my $line = shift #lines) {
next unless ($line =~ m/END OF HEADER/);
last;
}
append_file('writefile.txt', #lines);
I believe this will do what you need:
use strict;
use warnings;
my $find = 'END OF HEADER';
my $fileContents;
{
local $/;
open my $fh_read, '<', 'theFile.txt' or die $!;
$fileContents = <$fh_read>;
}
my ($restOfFile) = $fileContents =~ /$find(.+)/s;
open my $fh_write, '>>', 'theFileToAppend.txt' or die $!;
print $fh_write $restOfFile;
close $fh_write;
my $status = 0;
my $find = "END OF HEADER";
open my $fh_write, '>', $file_write
or die "Can't open file $file_write $!";
open my $fh_read, '<', $file_read
or die "Can't open file $file_read $!";
LINE:
while (my $line = <$fh_read>) {
if ($line =~ /$find/) {
$status = 1;
next LINE;
}
print $fh_write $line if $status;
}
close $fh_read;
close $fh_write;

read input file, match and remove data and write remaining lines to a new file

I am stuck trying to get this to write out the contents of the file. What I am trying to do is open an input file, filter out/remove the matched line and write to a new file. Can someone show me how to do this properly? Thanks.
use strict;
use warnings;
use Text::CSV_XS;
my $csv = Text::CSV_XS->new ({ binary => 1 }) or
die "Cannot use CSV: ".Text::CSV_XS->error_diag ();
open my $fh, "<:encoding(UTF-16LE)", "InputFile.txt" or die "cannot open file: $!";
my #rows;
while (my $row = $csv->getline ($fh)) {
my #lines;
shift #lines if $row->[0] =~ m/Global/;
my $newfile = "NewFile.txt";
open(my $newfh, '>', $newfile) or die "Can't open";
print $newfh #lines;
}
$csv->eof or $csv->error_diag ();
close $fh;
Open the output file outside of the loop. As you read each line, decide if you want to keep it. If yes, write to output file. If not, don't do anything.
Something like the following (untested):
use strict;
use warnings;
use Text::CSV_XS;
my ($input_file, $output_file) = qw(InputFile.txt NewFile.txt);
my $csv = Text::CSV_XS->new ({ binary => 1 })
or die sprintf("Cannot use CSV: %s\n", Text::CSV_XS->error_diag);
open my $infh, "<:encoding(UTF-16LE)", $input_file
or die "Cannot open '$input_file': $!";
open my $outfh, '>', $output_file
or die "Cannot open '$output_file': $!";
while (my $row = $csv->getline($infh)) {
next if $row->[0] =~ m/Global/;
unless ( $csv->print($outfh, $row) ) {
die sprintf("Error writing to '%s': %s",
$output_file,
$csv->error_diag
);
}
}
close $outfh
or die "Cannot close '$output_file': $!";
close $infh
or die "Cannot close '$input_file': $!";
$csv->eof
or die "Processing of '$input_file' terminated prematurely";