Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Modifying array data during print

by DrAxeman (Scribe)
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.

Thanks

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,
    Zaxo

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?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (3)
As of 2023-10-04 19:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?