1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

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

Discussion in 'Perl' started by rag84dec, Dec 4, 2008.

  1. rag84dec

    rag84dec New Member

    Joined:
    Jul 17, 2007
    Messages:
    49
    Likes Received:
    0
    Trophy Points:
    0
    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??
     
  2. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,646
    Likes Received:
    86
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    Code:
    open(H,'yourfile.txt');
    my @data = <H>;
    my $scalar_data = join(':',@data);
    
     
  3. murugaperumal

    murugaperumal New Member

    Joined:
    Feb 20, 2010
    Messages:
    15
    Likes Received:
    1
    Trophy Points:
    0
    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";
    }
    
    
     
  4. thillai_selvan

    thillai_selvan New Member

    Joined:
    Feb 20, 2010
    Messages:
    13
    Likes Received:
    0
    Trophy Points:
    0
    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
     

Share This Page