Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

How do I pipe some output to screen and some other selected output, out of the Perl script?

share|improve this question
add comment

2 Answers 2

up vote 3 down vote accepted

By using different file handles.

By default you'll have both STDOUT and STDERR. The print function in Perl is really short hand for print STDOUT.

In your terminal STDOUT is given the file handle 1 and STDERR is given the file handle 2.

Here's an example of printing to each file handle and redirecting each to /dev/null.

$ perl -e 'print STDOUT "foo\n"; print STDERR "bar\n";'
foo
bar
$ perl -e 'print STDOUT "foo\n"; print STDERR "bar\n";' 1> /dev/null
bar
% perl -e 'print STDOUT "foo\n"; print STDERR "bar\n";' 2> /dev/null
foo
  • The first command prints both.
  • The second command throws away STDOUT and prints only STDERR
  • The third command throws away STDERR and prints only STDOUT

You can also declare your own file handles (e.g., a log file) and print to that instead. See perldoc -f open.

share|improve this answer
    
I cant run perldoc, the system crashes. Could you note how to declare my own non-file handle? –  Hermann Ingjaldsson Jul 17 '12 at 19:45
    
Just print to STDOUT. It will go to the screen. –  bahamat Jul 17 '12 at 19:46
    
i know that, there is STDOUT and STDERR, but i need to make my own, third handle which i can pipe specifically out of the program. –  Hermann Ingjaldsson Jul 17 '12 at 19:47
    
Maybe you can clarify your question with some example code and where you want the output to go. –  bahamat Jul 17 '12 at 19:49
    
I want some output to go to the screen, and some to be piped by 'number> some_bash_script'. Sorry but the sample code is exactly what I'm missing. –  Hermann Ingjaldsson Jul 17 '12 at 19:52
show 4 more comments

you probably want to read the perlipc documentation, in particular the section on Named Pipes.

http://perldoc.perl.org/perlipc.html#Named-Pipes

perlipc - Perl interprocess communication (signals, fifos, pipes, safe subprocesses, sockets, and semaphores)

If you need two-way (read & write) communication with an external program, then the IPC::Open2 or IPC::Open3 modules (standard perl lib, also documented in the URL above) will be useful.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.