0

I have this code which reads a file and then prints each string separated by a space in the next line in another file output1.txt. What I am wondering is if i remove $/ , it takes only the first line of uart1.txt. What is local doing here and in the end file handle is returned in $data? Is there any way I can do this task?

#!/usr/local/bin/perl

open STDOUT, ">", "output1.txt" or die "$0: open: $!";

use strict; 
use warnings;

my $data= do {
open my $fh , '<','D:\perl_learning\uart1.txt' or die $!;
 local $/;
<$fh>;
};

while($data =~ /(\S+)/g)
{
my $word=$1;
printf"%s\n",$word; 
};    
Grace90
  • 205
  • 3
  • 19

1 Answers1

1

$/ is the record separator which is used for reading bits of a file at a time in a while loop. By default it's 'new line'.

However it's bad form to change it globally, because it may break other bits of your program.

local avoids this problem, by scoping the change to the current scope (practically 'this set of {}'). By default - when you localize in this way, it sets the value to undef. Which means you'll read the whole file in one go.

So what this means is - read everything in $fh into $data but don't mess with $/ globally.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
Sobrique
  • 52,974
  • 7
  • 60
  • 101
  • ok got it so $/ now becomes local to the file so it reads the file in one go just as by default it will read the line in one go...thanks a lot !! – Grace90 Mar 14 '15 at 12:45
  • No, it isn't local to the file. It is local to the block. – Quentin Mar 14 '15 at 18:11
  • By block u mean {} is it ? and in {} in the code its just opening the file in read mode so in this specific case it must be local to the file...please correct me if i am wrong! – Grace90 Mar 14 '15 at 19:24