Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Seekers of Perl Wisdom

( #479=superdoc: print w/replies, xml ) Need Help??

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
Avoiding circular references
3 direct replies — Read more / Contribute
by frazap
on Dec 06, 2019 at 05:25

    I came to this Is there an advantage to storing references to objects in an attribute instead of the object itself?. Applying find_cycle from Devel::Cycle in my own script showed that I had a lot of circular references.

    I realized most of them were due to storing "external" objects' reference in $self current object, many of these were in fact not needed in methods call. But in some methods I had to use an object received in the constructor.

    See for example the code below. The circular reference is suppress with a call to weaken (but the second call to do_something fails).

    use strict; use warnings; use Devel::Cycle; package A; sub new { my ( $class, $href ) = @_; my $self = { dbi => $$href{dbi} }; $self->{helper} = Helper->new( helper_function => sub { $self->this_is_from_A(@_ +) } ); bless $self, $class; } sub do_something { my $self = shift; $self->{helper}->called_from_helper(); } sub this_is_from_A { my ( $self, $arg ) = @_; print "$arg\nthis_is_from_A using $self->{dbi}\n"; } package Helper; #use Scalar::Util qw/weaken/; sub new { my $class = shift; my %def = ( a => "something" ); my %arg = ( ref $_[0] eq "HASH" ? ( %def, %{ $_[0] } ) : ( %def, + @_ ) ); my $self = \%arg; bless $self, $class; } sub called_from_helper { my $self = shift; print "called_from_helper\n"; $self->{helper_function}->("param from Helper"); #weaken($self->{helper_function}); } package main; my $a = A->new( { dbi => "some dbi object" } ); $a->do_something(); $a->do_something(); find_cycle($a);

    Using a sub ref instead of a method calls to this_is_from_A in the code ref pass with helper_function eliminates the circular reference because the code can access the $href->{dbi} directly.

    use strict; use warnings; use Devel::Cycle; package A; use Scalar::Util qw/weaken/; sub new { my ( $class, $href ) = @_; my $self = { dbi => $$href{dbi} }; $self->{helper} = Helper->new( helper_function => sub { $self->this_is_from_A(@_ +) } ); bless $self, $class; } sub do_something { my $self = shift; $self->{helper}->called_from_helper(); } sub this_is_from_A { my ( $self, $arg ) = @_; print "$arg\nthis_is_from_A using $self->{dbi}\n"; #weaken($self); } package Helper; #use Scalar::Util qw/weaken/; sub new { my $class = shift; my %def = ( a => "something" ); my %arg = ( ref $_[0] eq "HASH" ? ( %def, %{ $_[0] } ) : ( %def, + @_ ) ); my $self = \%arg; bless $self, $class; } sub called_from_helper { my $self = shift; print "called_from_helper\n"; $self->{helper_function}->("param from Helper"); #weaken($self->{helper_function}); } package main; my $a = A->new( { dbi => "some dbi object" } ); $a->do_something(); $a->do_something(); find_cycle($a); #find_weakened_cycle($a)

    But if the code from this_is_from_A was a long and complicated thing, wouldn't it clutter A->new and make it hard to understand and maintain ? Is there another solution ?

    Thanks for any comment

    frazap

    Update: complete the example 2 (end was missing)
Alternative to sort Hash
3 direct replies — Read more / Contribute
by IB2017
on Dec 06, 2019 at 04:28

    I need your expertise in this apparently small problem

    Given the following hash (installed TTS voices available on Windows 10):

    %voices = { 'Microsoft Hedda Desktop - German' => 3, 'Microsoft Haruka Desktop - Japanese' => 4, 'Microsoft Zira Desktop - English (United States)' => 0, 'Microsoft Hazel Desktop - English (Great Britain)' => 1, 'Microsoft David Desktop - English (United States)' => 2, 'Microsoft Huihui Desktop - Chinese (Simplified)' => 5 };

    I need to match a voice by its language. If there are more voices for one language, I just need to pick one. I do this as follows:

    use List::Util qw<first>; my $language='English'; my $voice = $voices{ ( first { m/$language/ } keys %voices ) || '' };

    So far so good. It pickis the first voice, in the above 0. Now the problem: for misterious Windows reasons, if there are more English Voices, the voice 0 can get in conflict with other voices, with the effect of Windows using the wrong one. My temporary and probably idea is to "jump" 0 if there are other English voices. If hashes would be sortable, I would simply sort the has by its value (from big to small).

    %voices = { 'Microsoft Huihui Desktop - Chinese (Simplified)' => 5 'Microsoft Haruka Desktop - Japanese' => 4, 'Microsoft Hedda Desktop - German' => 3, 'Microsoft David Desktop - English (United States)' => 2, 'Microsoft Hazel Desktop - English (Great Britain)' => 1, 'Microsoft Zira Desktop - English (United States)' => 0, };

    With a hash ordered like this, if there are more than 2 English voices, "0" will never be picked up.

    Any compact idea I am unable to think of?

use constant; RHE of solo confusing in list
4 direct replies — Read more / Contribute
by perl-diddler
on Dec 05, 2019 at 21:46
    I ran into this, and quickly took the path of least resistance, but had something like this:
    use constant { zed => 0, one => 1, repos => (qw(oss non-oss debug)), two => 2, }; #output: Constant name 'non-oss' has invalid characters at -e line 3. BEGIN failed--compilation aborted at -e line 7.
    Grumble. So I changed it:
    tperl use constant { zed=>0, one=>1, two=>2, }; use constant repos=>(qw(oss non-oss debug)); '
    Later when I saw this section again, I forgot why I split it...and tried combining it again with same results. Tried breaking things apart, but not seeing the diffs visualized:
    > tperl # (alias tperl='perl -I/home/law/bin/lib -we'\''use strict; us +e P;') our $k; BEGIN{our $k={ zed => 0, one => 1, repos => [qw(oss non-oss debug)], two => 2, };} use constant $k; use constant repos2=>(qw(oss non-oss));'
    Had to put assignment to k in BEGIN block for use-constants to see its value. But now no errors, but feeling uneasy about the result, I added some P statement to show me the structure(s):
    tperl our $k; BEGIN{our $k={ zed => 0, one => 1, repos => [qw(oss non-oss debug)], two => 2, };} P "k=%s", $k; use constant $k; use constant repos2=>(qw(oss non-oss debug)); P "repos=%s", [repos]; P "repos2=%s", [repos2];' #output: k={one=>1, two=>2, zed=>0, repos=>["oss", "non-oss", "debug"]} repos=[["oss", "non-oss", "debug"]] repos2=["oss", "non-oss"]
    Definitely a problem -- in this "solution"sic. Repos isn't a list, but a ref to a list. Grrr. Tried putting an array around the list:
    repos => @{[qw(oss non-oss debug)]},
    But then, fail:
    Constant name 'non-oss' has invalid characters at -e line 10. BEGIN failed--compilation aborted at -e line 10.
    I should just give up -- not worth the hassle, but does anyone see an easy way to combine these two constant definitions so that 1 statement will suffice for 2? Don't waste too much time...since I'll have already gone to the separate definition to move on, but sure seems a somewhat quirky situation, where because the definition in 1 def results in repos+defintion being combined with the outer list (because it is a list within a list, ala this mistake:
    my ($x,$y) = (qw(1 2 3), qw(4 5 6));
    Which we'd more quickly recognize as a problem if it was written:
    my ($x,$y) = ( (1,2,3), (4,5,6));
    Which most would see as a standard list-flattening gotcha. Which I skimmed over when I tried to combine my constant statements due to thinking that "qw" somehow would group them... Bzzzt. Anyway, Just don't see a safe & easy way to combine the definitions. Counterpoint?

    Thanks!

Perl appears to be dropping last character of line
5 direct replies — Read more / Contribute
by cmarra
on Dec 05, 2019 at 19:53

    Hi -- Disclaimer: I'm very new to Perl. Please forgive any offensive coding practices.

    I'm working through a file parse. The first few lines of the file are below the "***". Note that the first 2 lines of the file have blank spaces after the visible text, whereas on the following lines there are no spaces after the last visible character. (You'll have to trust me on that; I'm not sure it'll be obvious in this post.)

    This is all happening in a subroutine to which I pass in the array containing the file contents. When I shift through the array and get to the 4th line (" Year 2019") and print it, I get ("Year 201"). I've confirmed the same phenomenon further down in the file, where the last character is dropped when it's the last character on the line.

    Thanks in advance,

    Carol

    Code is as follows:

    sub read_gage_header { my ($data, $header, @headers, $ettb_no, $year); $data = shift; #Now get ettb_no $header = $data->[0]; @headers = split / /, $header; #NOTE: this print yields expected results print "HEADERS before ettb_no @headers\n" if defined ($debug); #NOTE: this gets the proper ettb_no $ettb_no = $headers[4]; #Skip to get to Year shift @$data; shift @$data; shift @$data; $header = shift @$data; #NOTE: this gives me "Year 201" print "HEADER before year $header\n" if defined ($debug); ... more code ...

    ****************** FILE STARTS HERE ********************************

    Gage Information - 240CN - 240 FEEDER CANAL SUPPLY TO 240 FEEDER FROM BELEN HIGH LINE CANAL + Year 2019 Month Day Time Height Discharge (mst) (HP ft) (QR cfs) ----- --- ---- ------ --------- July 29 1230 5.54 80 ... more data ...
Trouble installing modules for ActiveState Perl on a Windows server machine
2 direct replies — Read more / Contribute
by Bloehdian
on Dec 05, 2019 at 14:50

    Hello together,

    I am trying to install two CPAN modules (Log::Any and Config::Tiny) on a Windows 2012 server (Microsoft Windows Server 2012 R2 Standard 6.3.9600 N/A Build 9600) machine, having Activestate Perl V 5.26.3 installed) and get the following stuff:

    C:\>cpan -i Log::Any Can't locate Win32/Console.pm in @INC (you may need to install the Win +32::Consol e module) (@INC contains: C:\Perl64\site\lib C:\Perl64\lib) at C:\Perl +64\lib/Act ivePerl/Config.pm line 400. Compilation failed in require at C:\Perl64\lib/ExtUtils/MakeMaker.pm l +ine 9. BEGIN failed--compilation aborted at C:\Perl64\lib/ExtUtils/MakeMaker. +pm line 9. Compilation failed in require at C:/Perl64/lib/CPAN.pm line 48. BEGIN failed--compilation aborted at C:/Perl64/lib/CPAN.pm line 48. Compilation failed in require at C:/Perl64/lib/App/Cpan.pm line 288. BEGIN failed--compilation aborted at C:/Perl64/lib/App/Cpan.pm line 28 +8. Compilation failed in require at C:\Perl64\bin/cpan.bat line 23. BEGIN failed--compilation aborted at C:\Perl64\bin/cpan.bat line 23.

    Since even cpan did not work, I tried to install the missing Win32::Console via ppm, but to no avail.

    C:\>ppm install Win32-Console Downloading ActiveState Package Repository packlist...not found ppm install failed: Can't find any package that provides Win32-Console C:\>ppm search * *** no packages matching '*' found ***

    What is going wrong here? (on my Win 10 box Log::Any and Config::Tiny installed flawlessly)

Wrong calculation result with data retrieved with DBD::Oracle view
1 direct reply — Read more / Contribute
by yusanity
on Dec 04, 2019 at 22:24
    Hi, want to check with you guys anyone encountered intermediate issue of wrong calculation with data retrieved with DBD::Oracle view? My setup is as followings:- 1. DBI-1.642.tar.gz (https://metacpan.org/release/TIMB/DBI-1.642) 2. DBD-Oracle-1.76.tar.gz (https://metacpan.org/release/DBD-Oracle) 3. libnet-3.11.tar.gz (https://metacpan.org/release/SHAY/libnet-3.11) 4. Mail-Sendmail-0.80.tar.gz (https://metacpan.org/release/NEILB/Mail-Sendmail-0.80) 5. Time-Local-1.28.tar.gz (https://metacpan.org/release/DROLSKY/Time-Local-1.28) 6. Test-Inter-1.07.tar.gz (https://metacpan.org/release/Test-Inter) 6. Date-Manip-6.73.tar.gz (https://metacpan.org/release/SBECK/Date-Manip-6.73) 7. Carp-Clan-6.06.tar.gz (http://search.cpan.org/~kentnl/Carp-Clan-6.06/) 8. Storable-3.05_17.tar.gz (https://metacpan.org/release/RURBAN/Storable-3.05_17) 9. Bit-Vector-7.4.tar.gz (http://search.cpan.org/~stbey/Bit-Vector-7.4/) 10. Date-Calc-6.4.tar.gz (http://search.cpan.org/~stbey/Date-Calc-6.4/) 11. Data-Dumper-2.173.tar.gz (https://metacpan.org/release/XSAWYERX/Data-Dumper-2.173)
Cannot access CPAN Installs
4 direct replies — Read more / Contribute
by cristofayre
on Dec 04, 2019 at 14:28

    I am using Strawberry Perl, which resides at "C:/Strawberry" When I install modules via CPAN, for some reason best known to itself, it installs them in "C:/Users/Chris Brown/Perl5/lib/perl5" (For example, PDF::API2 can be found in "...perl5/PDF/API2"

    I have tried setting the "Perl5lib" path via My Computer / Enviroment variables to that shown in the first part above (It also showed my spaced name as "Chris~1" (DOS?), but changing it to the full name made no difference. I have also put the path in the main progrem:

    use lib qw(C:/Users/Chris Brown/perl5/lib/perl5);\n use PDF::API2;

    I have also tried combinations such as "perl5", "perl5/lib" but none of them work. The script simply cannot locate the library, asking me if I need to install it !!

    I don'tknow what to try next to get it to run. NB: Perl is installed correctly as it will run files from the shebang (#!/usr/bin/perl) It's just the CPAN modules it can't locate. (I even tried >use lib qw(C:/Users/Chris Brown/perl5/lib/perl5/PDF/API2.pm) but got nothing!)

    HELP !!
Truncate HTML String
1 direct reply — Read more / Contribute
by amacks
on Dec 04, 2019 at 10:08

    I'm trying to extract the beginning of an HTML string, in a way that returns legal HTML, basically to generate a summary page of blog entries for the index. For an example entry

    First a technological update - The code that drives this site is avail +able for free on <a href="https://github.com/amacks/vatican_mss">GitH +ub</a>. I've just merged in a rather complex change to create proper + shelfmark sorting, fixing things like numbers-stored-as-strings and +handling roman numerals. Two problems yet unfixed are Fonds <strong> +P.I.O</strong>, with the middle "I" reading as a roman numeral, and < +strong>Arch.Cap.S.Pietro</strong> where sub-set "I" is read as roman +1 and everything gets confused.</p>...

    a naive perl substr($_,0,100), returns text ending "free on <a href="htt", which is bad

Safely removing Unicode zero-width spaces and other non-printing characters
4 direct replies — Read more / Contribute
by mldvx4
on Dec 04, 2019 at 00:15

    (I've got a lot of data that I'm not able to duplicate inline here. When I try to paste it in, the problems go away. However, since this is for several automated scripts, manual intervention is not an option.)

    When I try to do a replacement s/\x{00A0}/ /gm; on my data, many other characters go bad, and end up looking like this:

    But he,<C2> along with so many of his<C2> fellow

    Note the <C2>s wedged in there. I do not have a "use utf8;" in place in this script, because if I add it, then it screws up nearly all the UTF-8 characters, in this way for an example:

    Desktop That‚<U+0080><U+0099>s More Elegant

    Which should look like this instead:

    Desktop Thatís More Elegant

    How should I go about approaching this problem. I think the solution might be to turn on UTF-8 but then what do I do to prevent the data from getting completely ruined?

Switch/Format to not interpret metacharacters in regex?
3 direct replies — Read more / Contribute
by mis
on Dec 03, 2019 at 20:15

    Hi Perlmonks,

    Is if possible to have a string interpreted as a literal without pre-escapting in a regex. Consider:

    #!/opt/local/bin/perl my $a = "Tick F***ing Tock"; my $b = "Friday night at 11:30pm the start of a new series, 'Tick F*** +ing Tock' explores..."; if ($b =~ /$a/) { print "..do something..\n"; }
    This will return:
    $ ./t.pl Nested quantifiers in regex; marked by <-- HERE in m/Tick F** <-- HERE + *ing Tock/ at ./t.pl line 5.
    Of course this will work:
    #!/opt/local/bin/perl my $a = "Tick F***ing Tock"; my $b = "Friday night at 11:30pm the start of a new series, 'Tick F*** +ing Tock' explores..."; $a =~ s/([\(\)\[\]\{\}\\\*\?\.\$\^\@\!\&])/\\$1/g; if ($b =~ /$a/) { print "..do something..\n"; }
    Result:
    $ ./t.pl ..do something..
    However there will result in a long list of escapes to make parsing safe as '$a' in my script is dynamic and not fixed like in this example... Also there will no doubt be a significant performance hit considering the number of times I'd be looping over the regex...

    Thanks in advance.


Add your question
Title:
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!
  • 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, 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
  • 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.
  • Log In?
    Username:
    Password:

    What's my password?
    Create A New User
    Chatterbox?
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others studying the Monastery: (9)
    As of 2019-12-06 15:08 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?
      Strict and warnings: which comes first?



      Results (156 votes). Check out past polls.

      Notices?