nejcPirc has asked for the wisdom of the Perl Monks concerning the following question:

Hello monks,

I have this "file.txt" with lines:
123||abc
234||frt
456||wer
and i would like to split them into 6 different scalars($numb1='123',$text1='abc',$numb2='234'...):
$i=1; foreach $line(@file) { chomp $line; ($numb."[$i]",$text."[$i]")=split(/\|\|/,$line);#problem?? $i++; }

Now i would like to display my scalars like:
for($j=0; $j<$i; $j++) { print $numb."[$i]||".$text."[$i]"; }
So this is my code and it must be something wrong with split line, concatenation....

Thanx for your help.
NEJC

Replies are listed 'Best First'.
Re: getting scalars out from txt file
by Roger (Parson) on Oct 15, 2004 at 12:00 UTC
    How about something like this - build an array of hash references:
    use IO::File; use Data::Dumper; my $f = new IO::File "file.txt", "r" or die "Can not open file"; my @vars; while (<$f>) { my ($d, $t) = $_ =~ /^(\d+)\|\|(\w+)$/; push @vars, { num => $d, txt => $t }; } print Dumper(\@vars);

    The structure will be something like:
    @vars = [ { num => '123', txt => 'abc' }, { num => '234', txt => 'frt' }, ... ];

    To retrieve the variables:
    $var[0]->{num}, $var[1]->{txt}, etc...
Re: getting scalars out from txt file
by ccn (Vicar) on Oct 15, 2004 at 10:47 UTC

    The problem is in the $numb."[$i]". This code produces a string value that is not a lvalue.

    Probably you may use an array

    foreach (@file) { chomp; my ($n, $t) = split /\|\|/; push @numb, $n; push @text, $t; } print "$numb[$_]||$text[$_]\n" for 0 .. $#@numb;
Re: getting scalars out from txt file
by nejcPirc (Acolyte) on Oct 15, 2004 at 10:44 UTC
    I did it like this:
    $i=1; foreach $line(@file) { chomp $line; ($numb,$text)=split(/\|\|/,$line); $numb[$i]=$numb; $text[$i]=$text; $i++; }
    Well, it's working...
      What's wrong with:
      ($numb[$i], $text[$i]) = ... Seems like $numb and $text are superfluous.
Re: getting scalars out from txt file
by ikegami (Patriarch) on Oct 15, 2004 at 15:21 UTC

    Manipulating the symbol table for something this trivial is guaranteed to give you headaches sooner rather than later. Do consider using a structure, such as the one in Roger's solution. It will also allow you to use use strict which will greatly help you find errors.

    btw, your print loop would be the following with his structure:

    for ($i=0; $i<@vars; $i++) { print $var[$i]{num}, '||', $var[$i]{txt}, "\n"; }

    or

    foreach (@vars) { { print $_->{num}, '||', $_->{txt}, "\n"; }