0

Have a look here Can Perl method calls be intercepted?

It shows how to rewrite the symbol table for a simple sub. The print command can take a list I believe, so what is the right way to intercept/rewrite it? I wish to get a program to delay printing while maintaining the same signature, and instead push the output into an array, pre-sort it, then regurgitate all the output at the very end.

Community
  • 1
  • 1
RichardTheKiwi
  • 105,798
  • 26
  • 196
  • 262

1 Answers1

7

Intercepting print itself isn't the way to go -- it has a number of operating modes, including writing to a file or socket. Instead, take a look at the select function, which can be used to change the default filehandle which print will write to.

Also, look at the concept of a "tied" IO handle, as used by IO::Capture.

cjm
  • 61,471
  • 9
  • 126
  • 175
  • Thanks! Is there a difference between `print "fun($abc $def)"` and `print("fun($abc $def)")` ? I know I should get a book and I probably will, but this is for a crash course – RichardTheKiwi Mar 17 '12 at 06:21
  • 1
    No -- they're absolutely 100% equivalent. –  Mar 17 '12 at 06:24
  • Thanks I thought there's some magic happening with the () like '' and "" are different in PHP. You're been a great help! – RichardTheKiwi Mar 17 '12 at 06:37
  • @Richard aka cyberkiwi, Parens can *usually* be omitted, so they are *usually* the same, but they are not 100% equivalent. `print("foo") && 4` vs `print "foo" && 4`, for example. – ikegami Mar 17 '12 at 10:29
  • I wrote a module [Tie::Select](http://p3rl.org/Tie::Select) which lets you localize the select call to a block. IMO its very useful. – Joel Berger Mar 17 '12 at 12:46