Reputation: 1420
I'm trying to follow this tutorial for my own code which basically right now reads a value into a scalar which is pushed into an array called states. However, it doesnt properly hash the function like in the tutorial and I believe its because the contents of the array isn't properly quoted.
I've tried
foreach (@states)
{
q($_);
}
and
push @states, q($key);
but neither produces the necessary output. Currently my output displays as
NY, NJ, MI , NJ
when using
print join(", ", @states);
I want it to display
'NY', 'NJ', 'MI' , 'NJ'
Upvotes: 4
Views: 5952
Reputation: 695
One other way:
use strict;
use warnings;
my @states = qw/ NY NJ MI NJ /;
my $output = join ', ', map qq/'$_'/, @states;
print $output;
Would result to a formatted list (string) of single quoted elements, each separated as you expect.
'NY', 'NJ', 'MI', 'NJ'
Upvotes: 1
Reputation: 35324
To add quotes around a value you can use double-quoted string interpolation:
"'$_'"
Or you can use string concatenation:
"'".$_."'"
So you can write your foreach
loop as follows:
foreach (@states) {
$_ = "'$_'";
}
Note that $_
must be assigned, otherwise the body of the loop has no effect (this is the case with your q($_);
code).
Full demo:
use strict;
use warnings;
my @states = qw(NY NJ MI NJ);
foreach (@states) {
$_ = "'$_'";
}
print(join(', ', @states ));
'NY', 'NJ', 'MI', 'NJ'
Upvotes: 1
Reputation: 241948
Take states, map them to quoted strings, join by comma:
my @states = qw( NY NJ MI );
print join ', ', map "'$_'", @states;
Upvotes: 13