Add quotes to all elements inside of an array in perl -
i'm trying follow this tutorial own code right reads value scalar pushed array called states. however, doesnt hash function in tutorial , believe because contents of array isn't quoted.
i've tried
foreach (@states) { q($_); } and
push @states, q($key); but neither produces necessary output. output displays
ny, nj, mi , nj when using
print join(", ", @states); i want display
'ny', 'nj', 'mi' , 'nj'
to add quotes around value can use double-quoted string interpolation:
"'$_'" or can use string concatenation:
"'".$_."'" so can write foreach loop follows:
foreach (@states) { $_ = "'$_'"; } note $_ must assigned, otherwise body of loop has no effect (this case q($_); code).
full demo:
use strict; use warnings; @states = qw(ny nj mi nj); foreach (@states) { $_ = "'$_'"; } print(join(', ', @states )); 'ny', 'nj', 'mi', 'nj'
Comments
Post a Comment