You may want to study perlopentut and perlipc.
In reply to Re^5: Test whether STDOUT is connected to a file by JavaFan in thread Test whether STDOUT is connected to a file by rovf