Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Perl (http://www.go4expert.com/forums/perl/)
-   -   perl script to read from a file and put in a scalar variable (http://www.go4expert.com/forums/perl-script-read-file-scalar-variable-t15398/)

rag84dec 4Dec2008 18:43

perl script to read from a file and put in a scalar variable
 
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??

pradeep 10Dec2008 16:11

Re: perl script to read from a file and put in a scalar variable
 
Code: Perl

open(H,'yourfile.txt');
my @data = <H>;
my $scalar_data = join(':',@data);


murugaperumal 25Feb2010 12:46

Re: perl script to read from a file and put in a scalar variable
 
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";
}


thillai_selvan 25Feb2010 14:03

Re: perl script to read from a file and put in a scalar variable
 
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


All times are GMT +5.5. The time now is 02:28.