I am Newbie to Perl script.
I want to do a read and write operation on a file. I will open a file in read and write mode (+<), and will write into a file. Now, I want read the file whatever I have written to it previously. Below is my code:
#!/usr/bin/perl
`touch file.txt`; #Create a file as opening the file in +< mode
open (OUTFILE, "+<file.txt") or die "Can't open file : $!";
print OUTFILE "Hello, welcome to File handling operations in perl\n"; #write into the file
$line = <OUTFILE>; #read from the file
print "$line\n"; #display the read contents.
When I am displaying the read contents it's showing a blank line. But the file "file.txt" has the data
Hello, welcome to File handling operations in perl
Why am I not able to read the contents. Whether my code is wrong or am I missing something.
The problem is that your filehandle position is located after the line you have written. Use the seek function to move the "cursor" back to the top before reading again.
An example, with some extra comments:
#!/usr/bin/env perl
# use some recommended safeguards
use strict;
use warnings;
my $filename = 'file.txt';
`touch $filename`;
# use indirect filehandle, and 3 argument form of open
open (my $handle, "+<", $filename) or die "Can't open file $filename : $!";
# btw good job on checking open sucess!
print $handle "Hello, welcome to File handling operations in perl\n";
# seek back to the top of the file
seek $handle, 0, 0;
my $line = <$handle>;
print "$line\n";
If you will be doing lots of reading and writing you may want to try (and not everyone suggests it) using Tie::File which lets you treat a file like an array; line access by line number (newline written automatically).
#!/usr/bin/env perl
# use some recommended safeguards
use strict;
use warnings;
use Tie::File;
my $filename = 'file.txt';
tie my #file, 'Tie::File', $filename
or die "Can't open/tie file $filename : $!";
# note file not emptied if it already exists
push #file, "Hello, welcome to File handling operations in perl";
push #file, "Some more stuff";
print "$file[0]\n";
This is a seemingly common beginner mistake. Most often you will find that reading and writing to the same file, while possible, is not worth the trouble. As Joel Berger says, you can seek to the beginning of the file. You can also simply re-open the file. Seeking is not as straightforward as reading line by line, and will present you with difficulties.
Also, you should note, that creating an empty file beforehand is not required. Simply do:
open my $fh, ">", "file.txt" or die $!;
print $fh "Hello\n";
open $fh, "<", "file.txt" or die $!;
print <$fh>;
Note that:
using open on the same file handle will automatically close it.
I use three-argument open, and a lexical (defined by my) file handle, which is the recommended way.
you do not need to add newline when printing a variable read in line by line mode, as it will already have a newline at the end. Or end of file.
You can use print <$fh>, as the print statement is in list context, it will extract all the lines from the file handle (print the entire file).
If you only want to print one line, you can do:
print scalar <$fh>; # put <$fh> in scalar context
Related
I have a file in which i have to replace all the words like $xyz and for them i have to substitutions like these:
$xyz with ${xyz}.
$abc_xbs with ${abc_xbc}
$ab,$cd with ${ab},${cd}
This file also have some words like ${abcd} which i don't have to change.
I am using this command
sed -i 's?\$([A-Z_]+)?\${\1}?g' file
its working fine on command line but not inside a perl script as
sed -i 's?\$\([A-Z_]\+\)?\$\{\1\}?g' file;
What i am missing?
I think adding some backslashes would help.I tried adding some but no success.
Thanks
In a Perl script you need valid Perl language, just like you need valid C text in a C program. In the terminal sed.. is understood and run by the shell as a command but in a Perl program it is just a bunch of words, and that line sed.. isn't valid Perl.
You would need this inside qx() (backticks) or system() so that it is run as an external command. Then you'd indeed need "some backslashes," which is where things get a bit picky.
But why run a sed command from a Perl script? Do the job with Perl
use warnings;
use strict;
use File::Copy 'move';
my $file = 'filename';
my $out_file = 'new_' . $file;
open my $fh, '<', $file or die "Can't open $file: $!";
open my $fh_out, '>', $out_file or die "Can't open $out_file: $!";
while (<$fh>)
{
s/\$( [^{] [a-z_]* )/\${$1}/gix;
print $fh_out $_;
}
close $fh_out;
close $fh;
move $out_file, $file or die "Can't move $out_file to $file: $!";
The regex uses a negated character class, [^...], to match any character other than { following $, thus excluding already braced words. Then it matches a sequence of letters or underscore, as in the question (possibly none, since the first non-{ already provides at least one).
With 5.14+ you can use the non-destructive /r modifier
print $fh_out s/\$([^{][a-z_]*)/\${$1}/gir;
with which the changed string is returned (and original is unchanged), right for the print.
The output file, in the end moved over the original, should be made using File::Temp. Overwriting the original this way changes $file's inode number; if that's a concern see this post for example, for how to update the original inode.
A one-liner (command-line) version, to readily test
perl -wpe's/\$([^{][a-z_]*)/\${$1}/gi' file
This only prints to console. To change the original add -i (in-place), or -i.bak to keep backup.
A reasonable question of "Isn't there a shorter way" came up.
Here is one, using the handy Path::Tiny for a file that isn't huge so we can read it into a string.
use warnings;
use strict;
use Path::Tiny;
my $file = 'filename';
my $out_file = 'new_' . $file;
my $new_content = path($file)->slurp =~ s/\$([^{][a-z_]*)/\${$1}/gir;
path($file)->spew( $new_content );
The first line reads the file into a string, on which the replacement runs; the changed text is returned and assigned to a variable. Then that variable with new text is written out over the original.
The two lines can be squeezed into one, by putting the expression from the first instead of the variable in the second. But opening the same file twice in one (complex) statement isn't exactly solid practice and I wouldn't recommend such code.
However, since module's version 0.077 you can nicely do
path($file)->edit_lines( sub { s/\$([^{][a-z_]*)/\${$1}/gi } );
or use edit to slurp the file into a string and apply the callback to it.
So this cuts it to one nice line after all.
I'd like to add that shaving off lines of code mostly isn't worth the effort while it sure can lead to trouble if it disturbs the focus on the code structure and correctness even a bit. However, Path::Tiny is a good module and this is legitimate, while it does shorten things quite a bit.
I am probably missing out on something becauseI started Perl today, so please excuse me if it's something very obvious.
I would like to load string from a file and then split it character by character.
I have done the following
use strict;
open my $fh, "<", "hello.txt" || die "Cannot open file!\n";
my $data = do { local $/ ; <$fh>};
print $data;
print join( ', ',(split( //, $data)));
close $fh;
When I execute this script the first print statement prints $data without problem, however the second print prints only the join string.
Hello, world!
,
I am running on Windows 7 machine with Strawberry Perl, I don't have access to Unix/Linux machine at the moment so I could not test it elsewhere.
This is probably an issue with the carriage return character "\r" – Windows line endings are \r\n, and a \r on its own moves back to the start of the line, overwriting what you have already written.
You could chomp $data first to remove the line ending, though this will only remove the last line ending.
You can also have Perl convert the Windows \r\n line endings to Unix \n line endings when reading in the file, by applying the :crlf IO layer:
open my $fh, "<:crlf", "hello.txt" or die "Cannot open file!\n";
(Note that it must be open … or die … or open(…) || die … but not open … || die …, because of operator precedence rules.)
So I am new to Perl and trying to simply open a directory, and list all its files. When I run this very simple code below trying to print everything in /usr/bin it will not work, and no matter what I try I keep getting told 'Could not open /usr/bin: No such file or directory'.
Any help would be much appreciated!
#!/usr/bin/perl
$indir = "/usr/bin";
# read in all files from the directory
opendir (DIR, #indir) or die "Could not open $indir: $!\n";
while ($filename = readdir(DIR)) {
print "$filename\n";
}
closedir(DIR);
Here is another place where the very basic troubleshooting step of use strict; and use warnings; has been omitted, and it would have told you exactly what was wrong.
Global symbol "#indir" requires explicit package name (did you forget to declare "my #indir"?)
Of course, you'd also have to fix a few other errors (e.g. my $indir = '/usr/bin';)
I would also suggest that readdir is not well suited for this job, and would tend to recommend glob:
#!/usr/bin/env perl
use strict;
use warnings;
my $indir = "/usr/bin";
# read in all files from the directory
foreach my $filename ( glob "$indir/*" ) {
print "$filename\n";
}
Note how this differs - it prints a full path to the file, and it omits certain things (like . and ..) which is in my opinion, more generally useful. Not least because another really common error is to open my $fh, '<', $filename or die $!, forgetting that it's not in the current working directory.
I created the following Perl one-liner in order to remove a word from a file
This Perl also escapes special characters such as # or $ or *, so every word that contains a special character will removed from the file.
How to change the Perl syntax in order to delete only the last matched word from a file and not all the words?
Example
more file
Kuku
Toto
Kuku
kuku
export REPLACE_NAME="Kuku"
export REPLACE_WITH=""
perl -i -pe 'next if /^#/; s/(^|\s)\Q$ENV{REPLACE_NAME }\E(\s|$)/$1$ENV{ REPLACE_WITH }$2/' file
expected results
more file
Kuku
Toto
Kuku
another example
when - export REPLACE_NAME="mark#$!"
more file
mark#$!
hgst##
hhfdd##
expected results
hgst##
hhfdd##
Use Tie::File to make this easier.
$ perl -MTie::File -E'tie #file, "Tie::File", shift or die $!; $file[-1] =~ s/\b\Q$ENV{REPLACE_NAME}\E\b/$ENV{REPLACE_WITH}/' file
Update: Rewriting as a program in order to explain it.
# Load the Tie::File module
use Tie::File;
# Tie::File allows you to create a link between an array and a file,
# so that any changes you make to the array are reflected in file.
# The "tie()" function connects the file (passed as an argument and
# therefore accessible using shift()) to a new array (called #file).
tie my #file, 'Tie::File', shift
or die $!;
# The last line of the file will be in $file[-1].
# We use s/.../.../ to make a substitution on that line.
$file[-1] =~ s/\b\Q$ENV{REPLACE_NAME}\E\b/$ENV{REPLACE_WITH}/;
Update: So now you've changed you requirements spec. You want to remove the last occurrence of the string, which is not necessarily on the last line of the file.
Honestly, I think you've moved past the kind of task that I'd write in command-line switches. It'd write a separate program that looks something like this:
#!/usr/bin/perl
use strict;
use warnings;
use Tie::File;
tie my #file, 'Tie::File', shift
or die $!;
foreach (reverse #file) {
if (s/\b\Q$ENV{REPLACE_NAME}\E\b/$ENV{REPLACE_WITH}/) {
last;
}
}
I'm trying to pipe syslogs to a perl script via syslog-ng but not all of the syslog entries make it through - maybe 1 in 3 actually happen.
I've looked all over the place and can't find anyone remotely having the problem that I have. It seems so simple but I can't find the answer!
Here's my syslog-ng setup:
source s_1 { tcp(port(514)); };
destination d_zen { program("/tmp/zen.pl"); };
log { source(s_1); destination(d_zen); };
and here's my perl script:
#!/usr/bin/perl
use strict;
use warnings;
$|=1
my $filename = "/tmp/zen.log";
open(my $fh, '>>', $filename) or die "could not open file '$filename' $!";
while ( <STDIN> ) {
print $fh <STDIN>."\n";
};
any thoughts?
Is your Perl line buffer disabled?
According to the syslog-ng manual, it can cause some problems:
"Certain external applications buffer the log messages, which might cause unexpected latency and other problems. For example, if you send the log messages to an external Perl script, Perl uses a line buffer for terminal output and block buffer otherwise. You might want to disable buffering in the external application."
Also, I don't know how your script reads the incoming messages (I don't now perl), but I think it should use a loop to keep reading incoming messages.
So syslog-ng should start the script once at startup, and it should keep running and processing messages.
HTH,
Regards,
Robert Fekete
I figured out the problem. My while loop wasn't built properly:
#!/usr/bin/perl
$|=1;
use strict;
use warnings;
my $filename = "/tmp/zen.log";
open(my $fh, '>', $filename) or die "could not open file '$filename' $!";
my $my_string;
while( <> ) {
$my_string .= $_;
print $fh "$my_string\n";
};