Digimon Digitizer 2
Digimon Digitizer 2

Reputation: 67

How to convert raw string to variable (variable --> $variable)?

How to convert string to variable (string variable --> $variable)?

Or a list of variables delimited by commas then convert to actual variables.

I have 2 files:

I need to match a whole row from the rows file based on a string, and name each row based from the column names file.

Example:

COLUMN NAMES FILE content

name,age,gender

ROWS FILE content

mar,44,m
rich,49,m
glenn,22,m

Now I have a variable string $who = 'glenn'

I will first match it on the ROWS FILE.

Then I need to name its matched contents with an actual variable with its name based on the COLUMN NAMES FILE.

Output:

$name = 'glenn';
$age = 22;
$gender = 'm';

I need something that dynamically changes, creating the needed variables and contents automatically by only updating the content files.

Upvotes: 2

Views: 232

Answers (1)

Sobrique
Sobrique

Reputation: 53478

What you're asking for, is not what you want. This is a bad idea for many many reasons, but they're outlined here: http://perl.plover.com/varvarname.html

What you need for this is a hash, and specifically a slice.

It works a bit like this:

my @header = qw ( A B C );
my @values = qw ( X Y Z );
my %combined;
@combined{@header} = @values; 
print Dumper \%combined; 

Gives:

$VAR1 = {
          'C' => 'Z',
          'A' => 'X',
          'B' => 'Y'
        };

(NB: Hashes are explicitly UNORDERED, so you get a random sequence each time you print. That's by design, because they're supposed to be accessed via keys anyway)

So with your data:

#!/usr/bin/env perl
use strict;
use warnings 'all'; 

open ( my $cols, '<', 'cols_file.txt') or die $!;
chomp ( my @cols = split /,/, <$cols> ); #just reads first line. 
close ( $cols );
open ( my $rows, '<', 'rows_file.txt' ) or die $!; 
while ( <$rows> ) {
    chomp;
    my %this_row;
    @this_row{@cols} = split /,/;
    push ( @all_rows, \%this_row );
}
close ( $rows );

print Dumper \@all_rows; 

You can then access individual elements from rows e.g.:

foreach my $row ( @all_rows ) {
    print $row -> {name},"\n";
 }

Upvotes: 9

Related Questions