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

Hello!

I have a text file which contains repeating entries as follows:

A: A_value B: B_value C: C_value A: A_value B: B_value C: C_value

My objective is to extract the values and store them to variables to later save into an array of hashes.

My current code is as follows:

my @data = readOnly( "Data.txt" ); my $i = 0; my $index = 0; my $a; my $b; my $c; while( $i < @data ) { if( $data[$i] =~ /A:/ ) { ( , $a) = split( /: /, $data[$i++] ); ( , $b) = split( /: /, $data[$i++] ); ( , $c) = split( /: /, $data[$i++] ); if( exists $baseline{$a} ) { $hash[$index++] = { a => $a, b => $b, c => $c, }; } } }

I've tried declaring the variables $a, $b and $c at the time of assignment as opposed to at the start of the sub and I've tried using a $garbage variable to store the first token of each split (although I don't need it).

I've gotten a variety of errors depending on how I set the code up, but ultimately Perl keeps telling me that $a is uninitialized when I use it in the check for existence.

Insight on why I'm having this issue and guidance on how to code this correctly would be GREATLY appreciated.

Thanks!

Replies are listed 'Best First'.
Re: Store result of split directly to variable(s)
by Athanasius (Archbishop) on Aug 22, 2014 at 16:32 UTC

    Hello Perl_Ally,

    Here are two methods:

    (1) Subscript the list returned by split:

    2:26 >perl -Mstrict -wE "my @data = ('A: A_value', 'B: B_value'); for + (@data) { my $a = (split /: /)[1]; say $a; }" A_value B_value 2:30 >

    (2) Assign the unwanted value to undef:

    2:30 >perl -Mstrict -wE "my @data = ('A: A_value', 'B: B_value'); for + (@data) { my (undef, $a) = split /: /; say $a; }" A_value B_value 2:30 >

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Yes, thank you!

Re: Store result of split directly to variable(s)
by AnomalousMonk (Archbishop) on Aug 22, 2014 at 16:33 UTC
    c:\@Work\Perl>perl -wMstrict -le "my $s = 'foo: notwantedonvoyage: bar'; my ($foo, undef, $bar) = split /: /, $s; print qq{'$foo' '$bar'}; " 'foo' 'bar'

      Thanks!