Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Scalar joining, concatenation, involving varying text

by ikegami (Pope)
on Jun 27, 2005 at 20:17 UTC ( #470373=note: print w/ replies, xml ) Need Help??


in reply to Scalar joining, concatenation, involving varying text

If everything was in a hash, it would be easier:

my %data; $data{a} = 1; $data{b} = 2; $data{c} = 3; my $combined = join ' ', map { "$_=$data{$_}" } grep { $data{$_} } sort keys %data;

There are two alternatives to using hashes.

1) Mucking around with the symbol table. This won't work if $a, $b, etc are lexical (my) variables.

our $a = 1; our $b = 2; our $c = 3; my $combined = join ' ', map { "$_->[0]=$_->[1]" } grep { $_->[1] } map { [ $_, do { no strict 'refs'; ${$_} } ] } qw(a b c);

2) Using eval. This is slow and risky.

my $a = 1; my $b = 2; my $c = 3; my $combined = join ' ', map { "$_->[0]=$_->[1]" } grep { $_->[1] } map { [ $_, eval('$'.$_) ] } qw(a b c);

Update: Added grep to every snippet to fix the bug crenz pointed out.

Here's the above without using map+grep:

my $combined; foreach (sort keys %data) { my $val = $data{$_}; # OR: my $val = do { no strict 'refs'; ${$_} }; # OR: my $val = eval('$'.$_); next unless $val; $combined .= "$_=$val "; } chop($combined);


Comment on Re: Scalar joining, concatenation, involving varying text
Select or Download Code
Re^2: Scalar joining, concatenation, involving varying text
by crenz (Priest) on Jun 27, 2005 at 20:37 UTC

    Uh, no. You're loosing the if-condition here, so your approach has different semantics than what the original poster wanted.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://470373]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2014-09-20 11:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    How do you remember the number of days in each month?











    Results (158 votes), past polls