Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

switching default line terminator?

by rmexico (Novice)
on Mar 21, 2006 at 14:04 UTC ( #538186=perlquestion: print w/ replies, xml ) Need Help??
rmexico has asked for the wisdom of the Perl Monks concerning the following question:

Is it possible to switch the line terminator for reading files in the middle of a program based on scope? I'm reading files that tend to have lines that span more than a single-line. So to do that I simply undef $/; Is it possible for me to redefine the line terminator once it's been undef'ed? I can't seem to get the $/ scoping to work, so once i have it undef'ed, i can't revert it. so...
#!/usr/bin/perl undef $/; &doStuff(); &foo(); sub doStuff { # want to read the file as a single string.... open TMP, "<somefile.txt"; my @file = <TMP>; close TMP; # do more stuff with that file... } sub foo { ## here i would want to read the file line-by-line $/ = '\n'; open TMP, "<otherfile.txt"; my @file = <TMP>; close TMP; }
thanks in advance

Comment on switching default line terminator?
Select or Download Code
Re: switching default line terminator?
by rafl (Friar) on Mar 21, 2006 at 14:08 UTC

    Use the 'local' keyword

    my $filename = 'foo.txt'; open my $fh, '<', $filename or die; my $content; { local $/ = undef; $content = <$fh>; } # $content contains the full file content now.

    Cheers, Flo

Re: switching default line terminator?
by CountOrlok (Friar) on Mar 21, 2006 at 16:07 UTC
    Try this:
    #!/usr/bin/perl use strict; doStuff(); # no need for & foo(); sub doStuff { # want to read the file as a single string.... local $/; # if you don't set it to anything, it is undefined open TMP, "<somefile.txt"; my $file = <TMP>; # $file since you are putting the whole file into + a scalar, not a list close TMP; # do more stuff with that file... } sub foo { ## here i would want to read the file line-by-line open TMP, "<otherfile.txt"; my @file = <TMP>; close TMP; }
    -imran

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://538186]
Approved by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2014-12-27 05:39 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    Is guessing a good strategy for surviving in the IT business?





    Results (176 votes), past polls