Piping to perl script

Code junkies hangout here

Moderators: ChrisThornett, LXF moderators

Piping to perl script

Postby drax » Fri May 21, 2010 1:23 pm

Hi,
I'm a perl newbie but it seems like it's now part of my job...
How can I capture the name of a file being piped to a perl script ?

I have this;

cat myfile | complicated.pl


It's a logfile analyser that's built around a while(<STDIN>) loop and outputs a digest. I need to be able to tell what myfile is within the script. I've tried variations on ARGV but I think they'd only work if the script was called like this;

complicated.pl myfile

Which I can't do, basically coz I'd have to rewrite the script and my level of perl knowledge is self evident from this post :)

It's also got to handle logrotation, I was thinking it might be easier to amend the logrotate script or is there a way I can capture a HUP within complicated.pl get it to close its currently open files and start crunching the new log file ?
drax
 
Posts: 6
Joined: Thu Dec 01, 2005 12:37 pm

Postby nelz » Fri May 21, 2010 9:58 pm

You can't do this reliably because your script is not getting the data from the file, it is getting it from standard input. It doesn't even know of the existence of the file.

As for the log rotation, why reinvent the wheel? Call the standard logrotate program to do this job.
"Insanity: doing the same thing over and over again and expecting different results." (Albert Einstein)
User avatar
nelz
Site admin
 
Posts: 8468
Joined: Mon Apr 04, 2005 11:52 am
Location: Warrington, UK

Postby tweetiepooh » Tue Jun 22, 2010 11:54 am

It's not that hard to change your script.

Simply put an open() call in. I've put the file name in a variable as later you can pass the file name in and just change how you set $filename.

Code: Select all
my $filename = "myfile";
open my $filehandle, '<', $filename or die "Can't open $filename\n";

Then change <STDIN> to use file handle

Code: Select all
while (my $line = <$filehandle>) {
   # do something with $line
}
close $filehandle;
User avatar
tweetiepooh
 
Posts: 10
Joined: Fri Jun 30, 2006 4:02 pm

Postby geek73666 » Wed Mar 30, 2011 6:59 am

You could always do something like cat file | complicated.pl file, and use $ARGV[0] as the file name. :)
geek73666
 
Posts: 4
Joined: Wed Mar 30, 2011 6:37 am


Return to Programming

Who is online

Users browsing this forum: No registered users and 0 guests