Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Rhinorhino on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

parameters with perl -w -i~ -n 2

Status
Not open for further replies.

noahgrad

Programmer
Joined
Dec 26, 2005
Messages
2
Location
DE
I am using perl -w -i~ -n inorder to filter lines from a file.
My script name is filter.pl
I use it by: filter.pl <file name>

If my file ends without newline : for example in "jjjjj"
I want to add to it a new line.

I thought to add in the END block \n to the file - The problem is that "print" prints to stdout instead of the file
and I don't have the file name (It is not in $1)
I also tried to get the file name during the loop and save it in a variable but again $1 is empty.
Please help.

Code example:
perl -w -i~ -n
BEGIN {
$filename = $1;
}
$filename = $1
s/(\S+)-@[0-9]+/$1-@<index>/g;
END{
print "\n to file";
};
 
@ARGV is a global array that holds the command-line arguments. In your example of "filter.pl <file name>", @ARGV should contain the <file name> part of the command.
 
@ARGV doesn't get filled when editing inplace. When you're reading from <>, $ARGV holds the filename of the file currently being processed. This is what you're looking for, I think:
Code:
#!/usr/bin/perl -w -i~ -n

s/(\S+)-@[0-9]+/$ARGV-@<index>/g;
print;
print "\n" if ( eof && !/\n$/ );
 
OK. What I said above about @ARGV isn't *quite* true. When using the -p or -n switches, @ARGV is shifted internally to get the filenames (i.e. the filename is removed from the array before the filehandle to that file is opened). You could therefore use $ARGV[0] in a BEGIN block, but not in the body of your code, as it would at that point be the filename of the *next* file to be processed (assuming more than one), rather than the current file).

Hope that clears up any confusion I may have caused.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top