Beefy Boxes and Bandwidth Generously Provided by pair Networks Cowboy Neal with Hat
The stupid question is the question not asked
 
PerlMonks  

Re: Scalar joining, concatenation, involving varying text

by ikegami (Patriarch)
on Jun 27, 2005 at 16:17 UTC ( [id://470373]=note: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.


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);

Replies are listed 'Best First'.
Re^2: Scalar joining, concatenation, involving varying text
by crenz (Priest) on Jun 27, 2005 at 16: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
Domain Nodelet?
Node Status?
node history
Node Type: note [id://470373]
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.