I would recommend that you first try this from the psql prompt, and only then try to put it in your code. I will also warn you that you are about to experience leaning toothpick syndrome.

Suppose you want to match the pattern /branch.\d+/. Well for postgres you need to pass that in as a string and every \ needs to be doubled to escape them because \ already has meaning. So you get 'branch.\\d+'. But in Perl \ is special, so to pass that into postgres you have to write 'branch.\\\\d+'.

If you are very sure that $root has no escape characters in it, you can write something like

$sth_get_branch_list = $dbh->prepare(qq( SELECT branch FROM postgres_database WHERE tre +e = 'first_tree' AND branch ~ '$root.\\\\d+'; ));
and it should work. But be warned that interpolating variables directly into SQL is a serious security risk because it leads to the possibility of SQL injection attacks. So you are better off with something like:
$sth_get_branch_list = $dbh->prepare(q( SELECT branch FROM postgres_database WHERE tre +e = 'first_tree' AND branch ~ ? || '.\\\\d+'; ));
and then passing $root into execute. This will still not do the right thing if $root has regular expression metacharacters in it, but at least it isn't a major security risk.

In reply to Re: Perl and PostgreSQL regex by tilly
in thread Perl and PostgreSQL regex by chrishowe

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.