princepawn has asked for the wisdom of the Perl Monks concerning the following question:

If a particular sub will be reading a filehandle and it needs to use a certain value of $/, is there a way to set $/ for this filehandle once instead of using local $/ on each sub invocation?

sub special_read { my $fh = shift; local $/ = "<!>"; ## <--- how do avoid this on each call? <$fh> ; }

Replies are listed 'Best First'.
Re: Setting a filehandle attribute for just one filehandle
by bikeNomad (Priest) on Jun 27, 2001 at 05:12 UTC
    OK, I think this'll work (I tested this by making test1.txt a normal text file, and then translating every "\n" into "\007" into test2.txt):

    #!/usr/bin/perl -w use strict; package MyHandle; use Tie::Handle; use IO::Handle; use base 'Tie::StdHandle'; my %seps; sub READLINE { my $self = shift; local $/ = $seps{$self}; $self->SUPER::READLINE(@_); } sub set_input_separator { my $self = shift; $seps{$self} = shift; } sub DESTROY { delete $seps{shift}; } package main; my $fh = tie *FH2, 'MyHandle'; $fh->set_input_separator( "\007" ); open FH1, 'test1.txt'; open FH2, 'test2.txt'; while (<FH1>) { my $data1 = $_; chop($data1); my $data2 = <FH2>; chop($data2); print "(1)$data1\n(2)$data2\n"; }

    update: added DESTROY to avoid mem leaks

      I don't see how this solves the problem asked. You're still doing a local $/ = ... every time the file is read from. You're just doing it in a much more complicated manner. *shrug* The question was a little vague (IMHO) so I might be misinterpreting it...

      Basically, I don't think that it can be done. If it could, I think IO::Handle would've done it.

      bbfu
      Seasons don't fear The Reaper.
      Nor do the wind, the sun, and the rain.
      We can be like they are.

        The problem I heard asked was:

        How can I have a per-filehandle $/ so I don't have to do an explicit local $/ = something every time I change file handles?

        My solution answers this by moving the local $/ = ... out of the user's program entirely, and adding per-file-handle setting of $/. How is this not an improvement?

Re: Setting a filehandle attribute for just one filehandle
by bikeNomad (Priest) on Jun 27, 2001 at 04:45 UTC
    You can do this:

    use IO::Handle; $fh->input_record_separator( "<!>" );

    update: princepawn is right, there's only one $/ . I suppose you could tie the handle and change $/ around each READLINE.

      I'm afriad I don't agree with you. Per the IO::Handle manpage:
      The following methods are not supported on a per-filehandle basis. IO::Handle->format_line_break_characters( [STR] ) $: IO::Handle->format_formfeed( [STR]) $^L IO::Handle->output_field_separator( [STR] ) $, IO::Handle->output_record_separator( [STR] ) $\ IO::Handle->input_record_separator( [STR] ) $/