Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?

Modifying array data during print

by DrAxeman (Beadle)
on Aug 07, 2005 at 04:04 UTC ( #481606=perlquestion: print w/ replies, xml ) Need Help??
DrAxeman has asked for the wisdom of the Perl Monks concerning the following question:

In my @cols array, each element has an _ in it. I want to convert this into an , during output. My code looks like:
my %avgsHash; @avgsHash{ @cols } = map {to_decimal($_)} @avgs; print "Server,Statistic,Average\n"; printf("%s,%f\n", $_, $avgsHash{$_}) for @cols;
Current output looks like:
Server,Statistic,Average ERRWWW_CPUPCT,5.1221 ERRWWW_RAMPCT,12.2332

Currently I'm piping my output through "sed" to modify this. I'm hoping that I can get it done in the code. I've tried a s/_/\,/g during the printf, but that failed.


Comment on Modifying array data during print
Select or Download Code
Replies are listed 'Best First'.
Re: Modifying array data during print
by Zaxo (Archbishop) on Aug 07, 2005 at 04:18 UTC

    If you don't want to change the the @cols array as you print (your hash keys are untranslated), it's as simple as:

    for (@cols) { (my $changed = $_) =~ tr/_/,/; printf("%s,%f\n", $changed, $avgsHash{$_}); }
    That just makes a copy before doing translation.

    After Compline,

Re: Modifying array data during print
by davidrw (Prior) on Aug 07, 2005 at 14:10 UTC
    Sort of combining your attempt and Zaxo's solution (differs in that it constructs the hash differently; which is better depends on what you need these vars for later):
    my %avgsHash; my @cols2 = map { tr/_/,/; $_ } @cols2; @avgsHash{ @cols2 } = map {to_decimal($_)} @avgs; print "Server,Statistic,Average\n"; printf("%s,%f\n", $_, $avgsHash{$_}) for @cols2;
    Also note that commas don't need escaping in regex's. e.g. s/,/A/g and s/A/,/g will both work fine.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://481606]
Approved by davido
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (10)
As of 2015-12-01 10:37 GMT
Find Nodes?
    Voting Booth?

    What would be the most significant thing to happen if a rope (or wire) tied the Earth and the Moon together?

    Results (798 votes), past polls