perl script to read from a file and put in a scalar variable

Go4Expert Member
4Dec2008,18:43   #1
rag84dec's Avatar
Hi,
I need to read the content of a file data.txt
Code:
dat
data1
into a variable...@temp.
I am getting both the values in $temp[0]...

can anyone help me??..

else i want it in a scalar variable like
$temp1= dat:data1 ---something like this...delimited by a delimiter...

can anyone help me??
Team Leader
10Dec2008,16:11   #2
pradeep's Avatar
Code: Perl
open(H,'yourfile.txt');
my @data = <H>;
my $scalar_data = join(':',@data);
Go4Expert Member
25Feb2010,12:46   #3
murugaperumal's Avatar
Dear Friend,

You can use the following coding also. You can get the first line in the array of first index, second line in the second index .......

Here the file2 contains the following content
dat
data1

Code:
 
use strict;
use warnings;
use Data::Dumper;
my $i=0;
my @array;
my ($var,$j);
open(FH,'<file2');
while($var=<FH>)
{
 chomp($var);
 $array[$i] =$var;
 $i++;
}

for ($j=0; $j<$i;$j++)
{
print '$temp['.$j.']='.$array[$j]."\n";
}
Go4Expert Member
25Feb2010,14:03   #4
thillai_selvan's Avatar
According to your doubt I am getting the contents of the file in the different
indexes in the array.
I followed the following code

Code:
open FH,"data";
my @data = <FH>;
my $result;
print "First line : $data[0]";
print "Second line : $data[1]";
consider that the data file is having the following content
dat
dat1


Code:
foreach (@data)
{
    chomp($_);
    $result .= $_.':';
}
This is used to concatenate the values in a scalar variable with : separated values