in reply to Re: Strings with undefined variables?
in thread Strings with undefined variables?

Thanks! Yeah, I expected I could do something like the following. Note that the actual use case involves several URLs that would like to store in a hash. (Also, I've been using Perl for almost 20 years, mostly in text processing. Only dabbled in Python and don't care for it much.)

my %URLS = ( upload => 'https://somewhere.com/api1', process => 'https://somewhere.com/=GUID=/api2', ); my $guid = upload_file( $ARGV[0] ); my $rtn = process_file( $guid ); sub upload_file { my $fn = shift; # LWP::UserAgent stuff my $g = $ua->post( $URLS{ upload } . '?' . $fn ); return $g; } sub process_file { my $guid = shift; # LWP::UserAgent stuff ( my $this_url = $URLS{ process } ) =~ s/=GUID=/$guid/; my $result = $ua->post( $this_url ); return $result || 0; }
fnord

Replies are listed 'Best First'.
Re^3: Strings with undefined variables?
by bliako (Abbot) on Jan 04, 2019 at 14:09 UTC

    That's cool. And if you pass to your subs a hash of substitutions a-la 'GUID'=>123 you will have a very light template system ...

    bw, bliako

      I've done pretty much exactly this on many occasions. Works very well for specifying user visible strings in a separate file and referencing them by ID.

      #! /usr/bin/env perl use strict; use warnings; my %templates = ( url => 'http://something.com/api_stuff/%guid%' ); print format_template( url => guid => 1234 ); sub format_template { my $template_id = shift; my $template = $templates{$template_id}; my (%args) = @_; foreach (keys %args) { $template =~ s/%$_%/$args{$_}/; } return $template; }

      πάντων χρημάτων μέτρον έστιν άνθρωπος.

        exact and succinct