4

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'
Community
  • 1
  • 1
Zee
  • 1,321
  • 2
  • 18
  • 41
  • also @keys here represents the scalar value im adding into states (such as NY, NJ etc.) – Zee Mar 31 '15 at 22:54

3 Answers3

13

Take states, map them to quoted strings, join by comma:

my @states = qw( NY NJ MI );
print join ', ', map "'$_'", @states;
choroba
  • 231,213
  • 25
  • 204
  • 289
  • unfortunately im reading it in from a file and storing it into a scalar so i cant directly do the qw() method – Zee Mar 31 '15 at 23:07
  • 3
    but in your question you show you have a @states array; if you don't, please modify your question. – ysth Mar 31 '15 at 23:24
1

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'
TLP
  • 66,756
  • 10
  • 92
  • 149
bgoldst
  • 34,190
  • 6
  • 38
  • 64
1

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'