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

Hi brother monks,
This code of mine print the content of %hash into STDOUT. How can I make the desired output as stringified variable instead?
use Data::Dumper; my %hash = ( 'mus09r' => [ '0,-464,AAACCATCTTGAAAC', '0,-350,GGTTCAGGATGGTTT', '0,-75,AAAACATCGTGACAC' ], ) while (my ($file,$val) = each %hash) { print '>dataset\n"; print '$file\n"; print '>instances\n"; print join("\n",@{$val}),"\n"; }
Such that it gives this single string variable:
$VAR1 = ' >dataset mus09r >instances 0,-464,AAACCATCTTGAAAC 0,-350,GGTTCAGGATGGTTT 0,-75,AAAACATCGTGACAC '

Regards,
Edward

Replies are listed 'Best First'.
Re: Creating a Stringified Variable
by tirwhan (Abbot) on Dec 14, 2005 at 09:21 UTC

    Hmm, I'm not sure I understand your question. Fixing the syntax errors in your code (s.below) makes it print out exactly what you seem to expect.

    my %hash = ( 'mus09r' => [ '0,-464,AAACCATCTTGAAAC', '0,-350,GGTTCAGGATGGTTT', '0,-75,AAAACATCGTGACAC' ], ); while (my ($file,$val) = each %hash) { print ">dataset\n"; print "$file\n"; print ">instances\n"; print join("\n",@{$val}),"\n"; }

    If what you're looking to do is put the text into a variable instead, simply append to that variable instead of printing directly.

    use Data::Dumper; my %hash = ( 'mus09r' => [ '0,-464,AAACCATCTTGAAAC', '0,-350,GGTTCAGGATGGTTT', '0,-75,AAAACATCGTGACAC' ], ); my $string; while (my ($file,$val) = each %hash) { $string.=">dataset\n". "$file\n". ">instances\n". join("\n",@{$val}). "\n"; } print Dumper $string;

    Update: Appending to string instead of replacing it every hash iteration, as per Mandrake's suggestion (note to self: Duh!).


    Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. -- Brian W. Kernighan
      One suggestion. Use the dot (.) operator to append since the hash can have more that one key-value pair.
      my $VAR1 ; while (my ($file,$val) = each %hash) { $VAR1 .= ">dataset\n". $file."\n". ">instances\n". join("\n",@{$val})."\n"; } print $VAR1;
      Thanks
Re: Creating a Stringified Variable
by pajout (Curate) on Dec 14, 2005 at 09:18 UTC
    I am not sure that you are asking for something like as:
    my $ret = ''; while (my ($file,$val) = each %hash) { $ret .= ">dataset\n"; $ret .= "$file\n"; $ret .= "instances\n"; $ret .= join("\n",@{$val}); $ret .= "\n"; }
Re: Creating a Stringified Variable from a Data Structure
by planetscape (Chancellor) on Dec 14, 2005 at 14:14 UTC