If you have a question on how to do something in Perl, or you need a Perl solution to an actual real-life problem, or you're unsure why something you've tried just isn't working... then this section is the place to ask. Post a new question!

However, you might consider asking in the chatterbox first (if you're a registered user). The response time tends to be quicker, and if it turns out that the problem/solutions are too much for the cb to handle, the kind monks will be sure to direct you here.

User Questions
Write Matlab binary MAT-files from Perl
2 direct replies — Read more / Contribute
by Anonymous Monk
on Jul 25, 2014 at 14:19

    Hi guys,
    I'm trying to write matlab binary MAT files from Perl.
    Does anyone have a working routine/function that does that already?
    I guess I'm not the first one trying to do this... but couldn't find a solution on this website or other pages.

    I've been trying to follow this thread:
    which basically works, but only for arrays that are shorter than 9 elements...
    Arrays longer than that (in most cases) cannot be loaded correctly into matlab and produce the following error message:

    > ??? Error using ==> load > Unable to read MAT-file C:\tools\mat4.mat > > File may be corrupt.

    For example:
    This works fine:
    > mat4_write('foo', 1, 9, (1,2,3,4,5,6,7,8,9), *MAT);
    And this does not (generates the error message above when trying to load the file into matlab):
    > mat4_write('foo', 1, 10, (1,2,3,4,5,6,7,8,9,10), *MAT);

    I saw the mat4_write routine (from the link above) uses the 'pack' function in this way:
    print ($h pack ('l5Z*d*', $type, $m, $n, $imag, $len, $name, @a));

    I also noticed that the mat file created is very close to the needed format, but not identical...
    And by comparing the created file to a similar file created from matlab (with same data, for a reference) I saw they differ in 1 additional byte...

    I have never used the 'pack' function, and the help from the link below is hard to follow:
    I couldn't find a match there for the 'l5Z*d*' format the routine above uses...

    Can someone please help me with that...?
    Does anyone have a working conversion function?
    Please help!


XML::Twig how to find a parent's attribute
2 direct replies — Read more / Contribute
by slugger415
on Jul 25, 2014 at 13:53

    Hi Monks, quick question I couldn't find in the documentation (or didn't understand the syntax) for XML::Twig - how do I match a parent or ancestor's attribute? For instance, I have some XML:

    <p conref="hello"> <ul> <li>Bob</li> <li>Mary</li> </ul> </p>

    If I'm evaluating li elements, I want to know if one of its parents has a conref attribute set. What's the syntax for that?


    ... returns the parent, which would be ul in this case, but how do I match the ancestor that contains the attribute I'm looking for?

    The doc says this about parent:

    parent ($optional_condition)
    Return the parent of the element, or the first ancestor matching the $optional_condition

    Just not sure how to phrase the optional_condition here.

    thanks, Scott

Parsing a JSON response
2 direct replies — Read more / Contribute
by mcoblentz
on Jul 25, 2014 at 13:46
    Hello All,

    I am trying to parse a JSON response from a Google API and am having a bit of trouble figuring out what is the right syntax to get the correct field values.  The program flow is to call the API then map the responses into my variables.  So the call looks like this: 
    <$geocoder = Geo::Coder::Google->new(apiver => 3); eval { $latlong = $geocoder->geocode(location => $location); print Dumper($latlong); }; $map_coords = $latlong->{geometry}{location}{lat} . " +" . $latlong->{geometry}{location}{lng}; $country = $latlong->{address_components}{types}{count +ry}{long_name};

    My problem is in the mapping for $COUNTRY.  In the JSON response, which dumps as follows, I get an error in trying to grab the long_name of the country out of the types (which I thought was a hash, but according to the error, it isn't):
    $VAR1 = { 'formatted_address' => 'Johannesburg, South Africa', 'types' => [ 'locality', 'political' ], 'address_components' => [ { 'types' => [ 'locality', 'political' ], 'short_name' => 'Johannesburg', 'long_name' => 'Johannesburg' }, { 'types' => [ 'administrative_are +a_level_3', 'political' ], 'short_name' => 'Johannesburg', 'long_name' => 'Johannesburg' }, { 'types' => [ 'administrative_are +a_level_2', 'political' ], 'short_name' => 'City of Johanne +sburg Metropolitan Municipality', 'long_name' => 'City of Johannes +burg Metropolitan Municipality' }, { 'types' => [ 'administrative_are +a_level_1', 'political' ], 'short_name' => 'GP', 'long_name' => 'Gauteng' }, { 'types' => [ 'country', 'political' ], 'short_name' => 'ZA', 'long_name' => 'South Africa' } ], 'geometry' => { 'viewport' => { 'southwest' => { 'lat' => '- +26.2389231', 'lng' => '2 +7.942449' }, 'northeast' => { 'lat' => '- +26.1041199', 'lng' => '2 +8.1376001' } }, 'location' => { 'lat' => '-26.2041028', 'lng' => '28.0473051' }, 'location_type' => 'APPROXIMATE', 'bounds' => { 'southwest' => { 'lat' => '-26 +.2389231', 'lng' => '27. +942449' }, 'northeast' => { 'lat' => '-26 +.1041199', 'lng' => '28. +1376001' } } } }; Not a HASH reference at cvlt_jobs_2 line 239.
    If the correct answer is 'South Africa' (address_components >> types >> country >> long_name), how do I grab that? 
connect string for sybase
1 direct reply — Read more / Contribute
by fionbarr
on Jul 25, 2014 at 12:44
    I have been given the following:
    DB_URL=jdbc:jtds:sybase://ddd.ddd.ddd.dd:ddddd/xxxxxx DB_USERNAME=user DB_PASSWORD=password
    Can anyone suggest how I should format a connect string for DBI?
Tk::BrowseEntry set function -solved
2 direct replies — Read more / Contribute
by glenn
on Jul 25, 2014 at 11:40

    Hi monks. So because I love pain I want to know if anyone else has found such a solution to this bug lack of functionality. The BrowseEntry which provides a drop down has 3 functions: insert, delete, and get. I want a fourth 'set', rather than defining yet another global var as I already pass the obj to insert/delete I would love to be able to '->set(0)' to set the current value to index 0 of the list. Any suggestions or pointing in the correct direction would be appreciated. Thank you for your time.

Storing part of a regex in a variable
1 direct reply — Read more / Contribute
by jonneve
on Jul 25, 2014 at 11:37
    Hello all, I'm writing a rather complex script for converting C++ code to Pascal. A number of patterns or sub-pattern occur rather often, and therefore, I'm trying to put them into variables for later use. Here are my variables :
    $braces = qr/(?<braces>\{ ([^\{\}] | (?&braces))*? \} )/x; $brackets = qr/(?<brackets>\( ([^\(\)] | (?&brackets))*? \))/x; $identifier = qr/(?<identifier> \w+($brackets)?( \s*(\.|->)(?&identifi +er))?)/;
    The $brackets and $braces variables work as I expected, but the $identifier variable doesn't work right, for example :
    #This works $meth_impl =~ s/((?<identifier> \w+($brackets)?( \s*(\.|->)(?&identifi +er))?)) \s* \. \s* Trim\(\)/Trim($1)/xg; #This doesn't match anything: $meth_impl =~ s/($identifier) \s* \. \s* Trim\(\)/Trim($1)/xg;
    As you can see in the example above, I'm using the $brackets variable in both cases, and it works nicely. Could the problem be that my $identifier variable itself includes the $brackets variable? Do I need to eval it or something to force it to interpolate it correctly? Thanks in advance, Jonathan Neve
I am not able to install DBD::Sybase module using cpan on windows as well as Ubuntu
1 direct reply — Read more / Contribute
by ashish.gupta
on Jul 25, 2014 at 08:50
    Hi, I am not able to install DBD::Sybase module using cpan on windows as well as Ubuntu. I am getting below error when I am try to install DBD::Sybase perl module. Error : "cpan> install DBD::Sybase Running install for module 'DBD::Sybase' Running make for M/ME/MEWP/DBD-Sybase-1.15.tar.gz Fetching with LWP: http://cpan.strawberryperl.com/authors/id/M/ME/MEWP/DBD-Sybase-1.15.tar.gz Fetching with LWP: http://cpan.strawberryperl.com/authors/id/M/ME/MEWP/CHECKSUMS Checksum for D:\wamp\bin\cpan\sources\authors\id\M\ME\MEWP\DBD-Sybase-1.15.tar.gz ok CPAN.pm: Building M/ME/MEWP/DBD-Sybase-1.15.tar.gz Please set SYBASE in CONFIG, or set the $SYBASE environment variable at Makefile .PL line 120, <IN> line 44. Warning: No success on commandD:\wamp\bin\perl\bin\perl.exe Makefile.PL MEWP/DBD-Sybase-1.15.tar.gz D:\wamp\bin\perl\bin\perl.exe Makefile.PL -- NOT OK Running make test Make had some problems, won't test Running make install Make had some problems, won't install Stopping: 'install' failed for 'DBD::Sybase'. Could not read metadata file. Falling back to other methods to determine prerequ isites Failed during this command: MEWP/DBD-Sybase-1.15.tar.gz : writemakefile NO 'D:\wamp\bin\pe rl\bin\perl.exe Makefile.PL' returned status 512" Thanks In advanced. Please guide me what can i do for resolve this error. Thanks, Ashish
Matching/replacing a unicode character only works after decode()
3 direct replies — Read more / Contribute
by FloydATC
on Jul 25, 2014 at 06:10

    After hours of struggling with a seemingly simple problem involving utf8 I finally made it work -- but I have no clue why. Allow me to explain.

    I have a script which scrapes a particular web site for data about communication links. The data is utf-8 encoded and contains (among a great many other things) the unicode character 'GREEK SMALL LETTER MU' (U+03BC) which (after being scraped, put through several scripts, stored in MySQL, later extracted and presented on a web page) renders as "μ". My co-workers didn't really mind but after a couple of years it started to annoy me so much I reached the point where I just had to fix it. Today was that day.

    I wanted to replace all occurences of this character with either unicode character 'MICRO SIGN' (U+00B5) which renders as expected, or (even better) simply with the HTML entity &micro;.

    The method in question produces clickable links to present each commlink in many different contexts.

    sub commlink { my $self = shift; return "" unless $self->{'id'}; my $label = $self->{'label'}; $label =~ s/\x{00b5}/\&micro;/g; $label =~ s/\x{03bc}/\&mu;/g; # Looks almost exactly the same as &mi +cro; return "<A href=\"commlink.html?id=".$self->{'id'}."\" class=\"".$se +lf->{'state'}."\">".$label."</A>"; }

    I knew the data stored in MySQL was utf8, the string was untoched and the web page charset was specified as utf8. If I tried to change it, the norwegian characters on the same page would become garbled so I knew the encoding setting was sent and detected properly.

    So... utf8 in, no encoding/decoding or string mangling prior to the regex... and still the regex didn't match.

    The solution?

    sub commlink { my $self = shift; return "" unless $self->{'id'}; my $label = $self->{'label'}; $label = decode('utf8', $label); # Why? It's already utf8 and I need + it to stay utf8 $label =~ s/\x{00b5}/\&micro;/g; $label =~ s/\x{03bc}/\&mu;/g; # Looks almost exactly the same as &mi +cro; return "<A href=\"commlink.html?id=".$self->{'id'}."\" class=\"".$se +lf->{'state'}."\">".$label."</A>"; }

    My question is... Why?! Before decoding the utf8 string, how could the string go from input to output unchanged but fail to match the regex? Why do I need to decode the utf8 string to match an utf8 character when the string already prints as an utf8 character? This is so confusing...


    OK, thanks for the pointers. It sounds so very very simple in theory, but in practice... This system is made up from more than 50 different scripts and modules that shuffle data back and forth and present it via HTML, SVG, generates javascript, text messages, emails and what have you. After I started trying to fix things to "do it right" then absolutely everything broke. I'm going to need weeks to get on top of this.

    This is exactly why I have always hated Unicode. Why, oh why could I not have left this stupid bug alone.

    -- FloydATC

    Time flies when you don't know what you're doing

Subroutine & For loop
5 direct replies — Read more / Contribute
by Anonymous Monk
on Jul 25, 2014 at 06:08
    Dear Monks, I would like to call a subroutine repeatedly based on a condition from a for loop and each time pass different parameters. My code is calling the subroutine only the first time. I am not sure which is the correct format to call a subroutine from a for loop. Please help. Thank you!
Problem with creating Files
2 direct replies — Read more / Contribute
by David92
on Jul 25, 2014 at 05:31
    Hey Monks,

    This is a very big program, so it might be, that I wont get an answer here, due to not understanding what do I seek help for, I'll try my best to explain.


    I have a problem when I create HTML pages with PERL. I use 2 Arrays. In FirstArray there are more elements than in SecondArray.

    When I start to create HTML's, I use in one of the Navigation Menus the list of elements in FirstArray.

    When you chose one element in the menu, it will open a new HTML (firstArray1.html) that wil display some statistics in a chart.

    That HTML has two buttons below the chart: FirstArray and SecondArray (name of buttons).

    If you click on SecondArray it will switch from current HTML (firstArray1.html) to (secondArray1.html). And then again if you click on FirstArray button it will switch to (firstArray1.html). The problem is that the FirstArray has more elements than SecondArray. And those elements that are NOT in the SecondArray are causing problems: Lets say we are in firstArray5.html and by clicking SecondArray button the page will try to load secondArrray5.html - HOWEVER there is NONE, because secondArray does not have that element as firstArray has.

    I have to keep the code as it is (all other 1000 lines of code). I have a seperate sub where I create the buttons:

    sub createButtons{ ($outfile,$filename)=@_; $replace = 'ay'; $find = 'DFT'; if(index($filename, $find) != -1){ $filenameDFT = $filename; $filenameLAY = $filename; $filenameLAY =~s/$find/$replace/; print $outfile " <a href='./$filenameLAY' class='button_l +ay'>Layout</a> <a href='./$filenameDFT' class='button_dft'> +DfT</a>\n </div>\n"; } #print "$filenameDFT\n"; else { $filenameLAY = $filename; $filenameDFT= $filename; $filenameDFT =~s/$replace/$find/; print $outfile " <a href='./$filenameLAY' class='button_l +ay'>Layout</a> <a href='./$filenameDFT' class='button_dft'> +DfT</a>\n </div>\n"; } return(@OutputButtons) }

    Filename is for e.g. firstArray1.html. I use a foreach loop in other subs to go over all elements in firstArray and another to go through all elements of secondArray.

    In real example filename is: file1LAY.html and file1DFT.html ... that is why I use the index, because I need a button to work for every HTML (filename). I want to make it so, that if file does not exist (but the reference is stored in one of the Buttons) it should change the reference to '#'

    This is a hard challenge, but I am in despair, so atleast I can try to ask, someone might have an idea.


Add your question
Your question:
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!
  • 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, 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, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • Outside of code tags, you may need to use entities for some characters:
            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.