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

rag84dec's Avatar, Join Date: Jul 2007
Go4Expert Member
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??
0
pradeep's Avatar, Join Date: Apr 2005
Team Leader
Code: Perl
open(H,'yourfile.txt');
my @data = <H>;
my $scalar_data = join(':',@data);
0
murugaperumal's Avatar, Join Date: Feb 2010
Go4Expert Member
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";
}
0
thillai_selvan's Avatar, Join Date: Feb 2010
Go4Expert Member
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