I'm currently doing work on a Perl SDK for an HTTP API, and have hit a bit of a stumbling block with s///.

The API takes XML for input, and when adding or updating fields it will accept either the numeric field identifier or a formatted version of the field label/field name. For the formatting, the field name would be "Field Name" and the reformatted version would be "field_name".

Because it's an API I'd like to do that reformatting transparently, so the end user just has to type in the field name they want to use. I'm using the s/// regexp to do the formatting, but I'm in a situation where I'd like to use it inline but it only returns the number of substitutions performed. Is there any way to use the s/// inline and return the substitution's results?

Here's the code I'm using:

sub add_record($){ my ($self, $data) = @_; my $record=[]; foreach my $key (keys %{$data}){ push(@{$record}, { tag=>"field", atts=>{ ($key=~m{^\d+$} ? "fid" : "name") => ($key=~m{^\d+$} ? + $key : lc($key =~ s/[^a-z0-9]/_/ig)) }, value=>$data->{$key} }); } return post_api("API_AddRecord", $record); }

And here's how it would be used:

add_record({"Field Name"=>"Field Value"})

In reply to Using s/// Inline by Jason Hutchinson

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.