Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi,
I need to convert an array into a string. However I'm having problems figuring out how to do this. So far this is the code I'm using
use strict; use Data::Dumper; my (@array,@newarray); @array=("ABCDEF01","HIJKL678","VWXYZ123H"); foreach my $val (@array) { print " USERNAME like '"; print substr($val,0,4); print "%' OR +"; }
which produces
USERNAME like 'ABCD%' OR USERNAME like 'HIJK%' OR USERNAME like 'VWXY%' OR

The problem I'm having is that I don't want the final OR to be printed and I'm not sure how to put the result into a string so I end up with

$string="USERNAME like 'ABCD%' OR USERNAME like 'HIJK%' OR USERNAME like 'VWXY%"
Any help appreciated

Replies are listed 'Best First'.
Re: covert to string variable
by choroba (Cardinal) on Oct 28, 2010 at 14:21 UTC
    join is what you need.
Re: covert to string variable
by Marshall (Canon) on Oct 28, 2010 at 14:36 UTC
    #!/usr/bin/perl -w use strict; my (@array,@newarray); @array=("ABCDEF01","HIJKL678","VWXYZ123H"); print join (" OR ", map{"USERNAME like $_%"}map{substr($_,0,4)} @arra +y),"\n"; #perhaps better: print "USERNAME "; print join (" OR ", map{"like $_%"}map{substr($_,0,4)} @array),"\n"; __END__ USERNAME like ABCD% OR USERNAME like HIJK% OR USERNAME like VWXY% USERNAME like ABCD% OR like HIJK% OR like VWXY%
Re: covert to string variable
by james2vegas (Chaplain) on Oct 28, 2010 at 16:17 UTC
    Do something like this (always use placeholders when passing variables to your SQL DB):
    use strict; use Data::Dumper; my (@array,@newarray); @array=("ABCDEF01","HIJKL678","VWXYZ123H"); # join 'USERNAME LIKE ?'x3 with ' OR ' my $str = join(' OR ', ('USERNAME LIKE ?')x@array); # prints USERNAME LIKE ? OR USERNAME LIKE ? OR USERNAME LIKE ? print $str; my $sth = $dbh->prepare("SELECT * FROM users WHERE $str"); # use map to convert each username in @array to 'match%' # passes (ABCD%, HIJK%, VWXY%) to execute $sth->execute( map { substr($_,0,4) . '%' } @array );
      Great. This is exactly what I wanted to do. Thanks for reminding me about the placeholders
Re: covert to string variable
by Your Mother (Archbishop) on Oct 28, 2010 at 16:57 UTC

    SQL::Abstract can help greatly with this kind of thing.

    use SQL::Abstract; my @user = qw( ABCDEF01 HIJKL678 VWXYZ123H ); my @like = map { substr($_,0,4) . "%" } @user; my $sql = SQL::Abstract->new; my ( $statement, @bind ) = $sql->select("User", "*", { -or => { username => { LIKE => \@l +ike } } }); print $statement, $/; print join(", ", @bind), $/; # Then some variation upon: $dbh->prepare($statement)->execute(@bind); __END__ SELECT * FROM User WHERE ( ( username LIKE ? OR username LIKE ? OR use +rname LIKE ? ) ) ABCD%, HIJK%, VWXY%
Re: covert to string variable
by Anonymous Monk on Oct 28, 2010 at 17:18 UTC