How can I replace just the last occurrence in a string with a Perl regex? -


ok, here test (this not production code, test illustrate problem)

my $string = <<eos; # auto generated query                 select                         users.*                         , roles.label role_label                         , hr_orders.position_label                         , deps.label dep_label                         , top_deps.label top_dep_label                                         users                         left join $conf->{systables}->{roles} roles on users.id_role = roles.id                         left join (                                 select                                         id_user                                         , max(dt) max_dt                                                                         hr_orders                                                                         fake = 0                                 ,                                         ifnull(position_label, ' ') <> ' '                                 group id_user                         ) last_hr_orders on last_hr_orders.id_user = users.id                         left join hr_orders on hr_orders.id_user = last_hr_orders.id_user , hr_orders.dt = last_hr_orders.max_dt                         $join                                         $filter                 order                         $order                 $limit eos  $where = "where\nusers.fake = -1 , ";  $string =~  s{where}{$where}i;  print "result: \n$string"; 

code, generates query, ends simple s{where}{$where}i, replaces every occurence of where.

i want replace top-level (last occurence of where?) 'where users.fake = -1' (actually, more complex pattern, doesn't matter).

any ideas?

why want build sql queries hard-coding strings , making replacements on them? wouldn't like

my $proto_query = <<'eoq' select ... %s ... eoq  $query = sprintf $proto_query, 'users.fake = -1 , ...'; 

or (preferably, avoids lot of issues initial approach , above has) using module such data::phrasebook::sql make lot of things easier?

if wanted go string substitutions, you're looking like

my $foo = "foo bar baz moo"; $foo =~ s/(.*)where/$1where affe and/; $foo; # "foo bar baz affe , moo" 

that is, capturing as can until can't capture more without not having "where" follow captured, , inserting whatever captured captured again, plus whatever modifications want make.

however, note has various limitations if you're using mangle sql queries. things right, you'd have understand sql @ level. consider, example, select ... user.name = 'where'.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -

PostgreSQL 9.x - pg_read_binary_file & inserting files into bytea -