Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

The Monastery Gates

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

Donations gladly accepted

If you're new here please read PerlMonks FAQ
and Create a new user.

New Questions
Printing an element of a list not an array
4 direct replies — Read more / Contribute
by raghuprasad241
on Aug 25, 2016 at 11:13
    GMAN all,

    GMAN (Good Morning, Afternoon, Night) depending on where you are :-)

    Is it possible to print individual elements of a list with out putting them into an array ? I think putting the list into an array is a wastage of memory if you are just trying to print it. For e.g. I am trying to do below with no success

    perl -e 'use v5.10; say (localtime)[1]' syntax error at -e line 1, near ")[" Execution of -e aborted due to compilation errors.

    Am I missing something simple ?

    Thanks!
    A Monk!
Check multiple array elements for a single condition
4 direct replies — Read more / Contribute
by Anonymous Monk
on Aug 25, 2016 at 06:38

    Just a quick question - is there a shorthand form of this:

    if ($array[0] == 0 && $array[1] == 0)

    A statement that would check both elements [0] and 1 for the condition ==0 without having to repeat the statement?

howto parse (or determining end) of a line of perl
5 direct replies — Read more / Contribute
by perl-diddler
on Aug 24, 2016 at 20:26
    I have a little calc I wrote in perl that really just provides and eval & print loop for the user.

    I have made changes over the years, but one of the things that has always bothered me is, if I want to add a complex expression -- anything that is multi-lined, how to get my input loop to know when it needs more input OR when it doesn't (vs. _could_ take more input).

    My 'semi-model' for that would be something like bash, where if you type 'the beginning of a control structure, bash will change to a different prompt to indicate it wants more input.

    How might I do the same in my eval/print loop?

    As it is now, I can define functions on 1 line, for example, but there is no easy way to extend that to more than one line.

    I could force the use of an 'extend char', like backslash at the end of line -- but in bash, those are only needed if it is ambiguous -- i.e. if the line is already well formed, you need to enter '\' to tell bash to keep parsing. Ex. (using 'home>' as normal prompt):

    home> int a=1+1\ > +2; echo $a 4
    You can't enter partial *expressions* in bash and have it "auto continue" (that I know of). I.e.
    home> a=1+<cr> -bash: 1+: syntax error: operand expected (error token is "+")
    But I could enter a '\' at the end of line and continue it as I did above.

    Where bash works to auto-detect is in its control structures (or like if a quote is still open). Ex:

    home> for ((i=0;i<10;++i)); then<cr> > [...]
    On the 2nd line, it doesn't display the normal prompt, but a single greater than sign. How could I get my input/eval loop to get feedback from perl that I'm in the middle of a similar structure and change the prompt and not try to eval it?

    -------------

    Clarification: how can I do that w/o writing an entire perl parser? ;-)

Sending UDP Packets to MATLAB
5 direct replies — Read more / Contribute
by RadioEngineer
on Aug 24, 2016 at 16:01
    Hello ,

    My Background in Perl: 5 Days of Experience in using Perl

    Task where I am stuck at :

    1) I have a radio which outputs 10 values at a given time stamp. I need to send those 10 Values as a single UDP packet via Ethernet connected to Another Hardware managed by MATLAB/Simulink.

    2) I wrote a Perl Script which gives me a string of all values like $data = '2.2,4,6,7.43,23.34,11,45576,343,22,10' ..

    3) MATLAB/Simulink blocks (related to my hardware) doesn't accepts strings . It needs numbers of type (Boolean,int8,unit8,int16,uint16,int32,uint32,float,double) and have big Endian format...

    4) Coming to my application , I can only receive 32 Bit Word input data stream so that decode block converts back into an array of 10 numbers... (There is no way I can know the functionality of Decode block so that I can encode in the same way in my perl script.)

    Can anyone please help me in this regard as to tell how can i send those bunch of numbers in a single UDP packet.

    I believe its similar to pack/unpack functions in Perl . Except the fact that Unpack is Decode block in Simulink. I have to PACK the data to either of Datatypes above mentioned with any possible delimiters

Hash searching
2 direct replies — Read more / Contribute
by Oligo
on Aug 24, 2016 at 07:29

    Hello Monks,

    I'm trying to master the art of searching with hashes. I have a file with a list of search terms (one line = one term):

    J00153:42:HC5NCBBXX:6:1101:10896:14959 J00153:42:HC5NCBBXX:6:1101:10896:14959 J00153:42:HC5NCBBXX:6:1101:26616:20709 J00153:42:HC5NCBBXX:6:1101:27549:19935

    ...and a master file I want to search for those terms in (again, one line per record):

    J00153:42:HC5NCBBXX:6:1101:10896:14959 99 gnl|Btau_4.6.1|chr16 + 72729218 1 12M J00153:42:HC5NCBBXX:6:1101:27549:19935 83 gnl|Btau_4.6.1|chr8 + 49556412 1 7M

    I started by opening the query file and reading each line into an array. Then while-ing through the master file, returning matching lines where the array elements match the relevant part of the master file:

    # Open query file and read into array $queryfile = $ARGV[0]; open (QUERYFILE, $queryfile) or die "Cannot open query file\n"; @queries = <QUERYFILE>; close QUERYFILE; # Open main file $mainfile = $ARGV[1]; open (MAINFILE, $mainfile) or die "Cannot open searchable file\n"; # Search through main file while ($inline = <MAINFILE>) { @split = split /\t/, $inline; $ID = $split[0]; if (grep /$ID/, @queries) { print $inline; } else { } } exit;

    This works fine, but the files are huge and the code takes an age to run. So, I tried converting the array to a hash (array elements = hash keys, values all = 1) but I can't seem to get the pattern matching syntax right; the code runs much faster but nothing comes back. So far I have:

    # Open query file and read into array $queryfile = $ARGV[0]; open (QUERYFILE, $queryfile) or die "Cannot open query file\n"; @queries = <QUERYFILE>; close QUERYFILE; # Convert array to hash %hash = map {$_ => 1} @queries; # Open main file $mainfile = $ARGV[1]; open (MAINFILE, $mainfile) or die "Cannot open searchable file\n"; # Search through main file while ($inline = <MAINFILE>) { @split = split /\t/, $inline; $ID = $split[0]; if (defined $hash{$ID}) { print $inline; } else { } } exit;

    Any Perly wisodom greatly appreciated!

Advice wanted for debugging CPAN Testers failures
3 direct replies — Read more / Contribute
by pryrt
on Aug 23, 2016 at 11:59
    Fellow Monks,

    How do you go about debugging failures from CPAN Testers when your own configurations are not failing? I'd like advice, both in general, and anything you see in my specific examples below.

    For example, this test matrix has a bunch of failures -- but when I test on my machines, I cannot replicate the errors they are getting.

    Before releasing, I tested on a couple of different versions I have access to (strawberry perl 5.24.0_64 on Win7 and an ancient CentOS 4.6 linux 2.6.9-55 with perl 5.8.5), and neither failed my test suite. And since I've seen the CPAN Testers failures, I've started increasing my berrybrew installations to improve version coverage -- but so far, they've all passed, even when they've been on Perl versions that failed in the linux column.

    After I've exhausted available Strawberry installations, I will probably grab one of my linux virtual machines and start increasing perlbrew installations, and run through as many as I can there (I cannot install perlbrew or other local perls on the CentOS machine I noted, due to disk restrictions). But even with trying a new slew of versions, I cannot guarantee that I'll see the same failures that CPAN Testers is showing me.

    I know where I'll be looking for the specific errors: my expected values are wrong; the expected values were being generated by functions I thought were fully tested earlier in my test suite, so I'll have to look into that some more, and also see if maybe I should independently generate the expected values.

    But if I cannot replicate the exact failures from CPAN Testers, it's going to be harder to know I've solved the problem. When doing my last release to add features, I ended up submitting beta versions to CPAN, with extra debug printing, and waiting overnight while the CPAN Testers ran, then basing my fixes on changes in those results. But that's a rather slow debug process... and I noticed that every submission, I was getting fewer results from TESTERS: I think some of those auto-testers have some sort of submission limits, or otherwise remember that a particular module fails and stops testing new versions.

    Any advice, generic or specific, would be welcome.

Good Perl-based web Calendar Frameworks?
2 direct replies — Read more / Contribute
by Cody Fendant
on Aug 22, 2016 at 22:31

    I'm trying to set up a calendaring system at work (various events start or finish on any given day and I need to be reminded of them) and I'd like it to be something created in Perl.

    Any recommendations for a web framework/module which has good calendar functions? Obviously, online calendar output by day, week, month etc. would be good but also email functions to say "don't forget X happens today".

Devel::Cover for myfile.pl with different command-line input arguments
2 direct replies — Read more / Contribute
by tito80
on Aug 22, 2016 at 15:08
    Hi PerlMonks,

    I am a newbie and pardon my ignorance. I am trying to use Devel::Cover (DC) to get an idea of the code coverage of my my_file.pl ran with arg1 arg2, etc. as command-line input arguments. I am using Perl 5.8.9 with 1.23 DC. The steps I executed successfully to generate the html file are:

    1) perl -MDevel::Cover my_file.pl -arg1 <arg1_value> -arg2 <arg2_value>

    2) Devel-Cover-1.23/bin/cover cover_db --report=html

    Now, I do not have packages/modules to test directly. But I have the my_file.pl file which invokes several packages.

    And I need to test my_file.pl with several different combinations of command line i/p arguments (i.e. <arg1_different_value1>, <arg2_different_value_2>, etc.). All these test combinations are a part of my regression suite (you can think of the options written in a test.txt file sequentially) and I am trying to see if Devel::Cover can assure that I have 100% code coverage with these tests.

    While I can run the above in a for-loop, each time with different arguments, I am not sure if that is the best way since I will end up with 100's of html/report files that need to be merged for any meaningful purpose.

    Could you kindly provide some pointers?

    Thanks, Tito

How to display name of current package
3 direct replies — Read more / Contribute
by sylph001
on Aug 22, 2016 at 06:16

    Dear monks,

    Recently I tried to find a way to display the name of the perl package that the program is in, however didn't get any clue about this.

    Could you let me know if there is any special varaible or any other method that I can get the package name?

    Thanks a lot in advance

    For example, I'm writing a package in "MyModule.pm", and I need to display the package name when the program is executing this package, like in below:

    package MyPackage; use warnings; my $pkg_name = <how to know the package name?>; print "I'm currently in the $pkg_name package!"; exit 0;

Master Pages and OpenOffice::OODoc
1 direct reply — Read more / Contribute
by emav
on Aug 20, 2016 at 21:16

    I've been trying to process some XML files to create OpenOffice text documents and have been mostly successful so far. However, I would like to add page numbers in the footer, which should appear on all pages but the first couple of them where the title is supposed to appear.

    So far, I think I've figured out that the way to go about achieving this is through master/layout pages but I have been unable to accomplish the required task. Of course, it would be easier to simply produce the basic document and then edit it through LibreOffice to get what I need but... you know how it is! I've got to know now!

    So, the sample code below produces what I expect: An .odt document with the title on the first page without a page number in the footer and the text appears in the following pages with a page number in the footer. However, the problem seems to be that every page contains one paragraph only preceded by a page break.

    I guess the problem lies somewhere in the way I connect master/layout pages to the paragraph styles... or something... but I couldn't find any concrete examples on line to help me fix my mistake(s). I would appreciate any pointers because this is almost driving me crazy.

    Here's the sample code:

    #!/usr/bin/perl -w use strict; use warnings; use utf8; use Win32; use Encode; use OpenOffice::OODoc; use Data::Dumper::AutoEncode; ooLocalEncoding('utf-8'); my $curfolder = Win32::GetCwd(); my $outfolder = $curfolder . '\\out'; my $outfile = $outfolder . '\\test.odt'; my $doc = odfDocument( file => $outfile, create => 'text', opendocument => 0, ); my $styles = odfDocument( container => $doc, part => "styles", ); my $centerfooter = $styles->createStyle( 'centerfooter', family => "paragraph", properties => { "fo:margin-top" => "0.5cm", "fo:text-align" => 'center', }, replace => 1, ); my $headerstyle = $styles->createStyle( "header", family => "paragraph", parent => "Standard", properties => { "fo:margin-top" => "8cm", "fo:text-align" => "center", "fo:break-after" => "page", }, replace => 1, ); $styles->styleProperties( $headerstyle, -area => "text", "fo:font-size" => "200%", "fo:font-weight" => "bold", ); $styles->setAttributes( $headerstyle, "master-page-name" => 'header', ); my $regularstyle = $styles->createStyle( "regular", family => "paragraph", parent => "Standard", replace => 1, ); $styles->setAttributes( $regularstyle, "master-page-name" => 'pagenumbers', ); my $pagelayout = $styles->pageLayout("Standard"); my $titlepage = $styles->createMasterPage( 'titlepage', layout => $pagelayout, ); my $pnpage = $styles->createMasterPage( 'pagenumbers', layout => $pagelayout, ); my $pn = $styles->createParagraph( '', 'centerfooter' ); my $pg = $styles->textField( 'page-number', style => 'centerfooter' ); $styles->appendElement( $pn, $pg ); $styles->masterPageFooter( 'pagenumbers', $pn ); my $wordlist = $doc->appendParagraph( text => '', style => 'header', ); $doc->extendText( $wordlist, uc 'Main Title', 'header' ); my $regular = $doc->appendParagraph( text => 'Some text.', style => 'regular', ); $doc->appendParagraph( text => 'More text.', style => 'regular', ); $doc->appendParagraph( text => 'And some more.', style => 'regular', ); $doc->save;
Insert images on Mojolicious website
1 direct reply — Read more / Contribute
by pazt
on Aug 20, 2016 at 20:06

    Hi, monks

    I can't insert images on my Mojolicious projects. I'm converting my CGI script to Mojo. I'm Mojo newbie yet.

    My current app structure is:
    myapp |- myapp.pl |- lib | |- MyApp.pm | +- MyApp | +- Model | +- Users.pm |- t | +- login.t +- templates |- layouts | +- default.html.ep |- index.html.ep +- <b>protected.html.ep</b>

    It's an example from Mojolicious::Guides::Growing

    My questions are:

    1. How can I insert an image on protected.html.ep?
    2. Where should I store my image files?
    3. How should be?


    Thanks for help

Do I have to trick Split?
1 direct reply — Read more / Contribute
by $h4X4_&#124;=73}{
on Aug 20, 2016 at 08:12

    I found out something strange about split. I guess it will not parse blank content till there is something at the end...
    I have a string that splits at a comma,but when there are repeated delimiters at the end they will not be added to the array till there is something at the end like so...

    #!perl use warnings; use strict; use Data::Dumper; my $str = "ABC,123,,,,,,"; # just ABC and 123 #my $str = "ABC,123,,,,,,this"; # now it shows the blanks. my @elems = split ',', $str; print Dumper \@elems;
    Any other ways maybe regex or should I trick the array and then pop the last content out?

New Cool Uses for Perl
Displaying my PM post count and XP on an LCD with RPi::WiringPi
1 direct reply — Read more / Contribute
by stevieb
on Aug 24, 2016 at 20:50

    Well, I've finally released RPi::WiringPi v1.00. This uses the WiringPi::API wrapper that wraps the C-based wiringPi Raspberry Pi hacking software.

    Anyway, I thought I'd throw something together that's kind of silly to play around with it. A couple of points: a) I know this isn't the proper way to web-scrape, it's just an example ;) b) forgive the global variables. The interrupt code in wiringPi library does not allow you to pass in any parameters, so until I submit a possible patch, globals are all I have. This was not meant to be prod code :D

    The following code, infinitely looping every 60 seconds, scrapes my number of posts and XP from PerlMonks (in a *very* crude way), collects up the current time, then prints the data out onto an LCD display attached to my Pi:

    p: 1293 18:15 x: 10361

    Number of posts and then the time on the top line, XP on the bottom.

    We introduce a button connected to a pin, when pressed, triggers an interrupt, and the interrupt handler rewrites the bottom line with the amount of XP remaining until my next PM level, instead of current XP (changes from x: 10361 to r: 1638. Every button press flips this back and forth.

    Pics: before button press, and after button press.

    use warnings; use strict; use LWP::Simple; use RPi::WiringPi; use RPi::WiringPi::Constant qw(:all); # catch a sigint. This allows us to # safely exit the while() loop and perform # emergency LCD/pin cleanup. The main class # catches die() my $continue = 1; $SIG{INT} = sub { $continue = 0; }; # initialize a Raspberry Pi object using the # BCM GPIO pin numbering scheme my $pi = RPi::WiringPi->new(setup => 'gpio'); # prepare and initialize the LCD my $lcd = $pi->lcd; # the following list of args looks daunting, but # it's very straightforward, and the docs are # pretty clear my %args = ( cols => 16, rows => 2, bits => 4, rs => 21, strb => 16, d0 => 12, d1 => 25, d2 => 24, d3 => 23, d4 => 0, d5 => 0, d6 => 0, d7 => 0, ); $lcd->init(%args); # set up a pin with a button, and set an # interrupt handler to do something when # the button is pressed my $button_pin = $pi->pin(26); # we're going to interrupt when the pin # goes LOW (off), so we'll pull it HIGH # with the built-in pull up resistor. # only when the button is pressed, will the # pin briefly go LOW, and this triggers # an interrupt $button_pin->pull(PUD_UP); # the second arg to interrupt_set() is the # name of the perl sub I've defined below # that I want handling the interrupt $button_pin->interrupt_set( EDGE_FALLING, 'button_press' ); my $button_presses = 0; my ($posts, $xp, $next); while ($continue){ my ( $sec,$min,$hour,$mday,$mon, $year,$wday,$yday,$isdst ) = localtime(); $min = "0$min" if length $min == 1; # get my post and xp count from PM ($posts, $xp) = perlmonks(); # manually get xp needed for next level $next = 12000 - $xp; # set the LCD cursor to top row, first # column, and print my num of PM posts $lcd->position(0, 0); $lcd->print("p: $posts"); # sub for bottom line, because the # code needs to be called also in our # interrupt handler. What's printed depends # on the cumulative number of button presses display_xp(); # on top row of the LCD at column 12, # we print the time $lcd->position(11, 0); $lcd->print("$hour:$min"); print "$hour:$min posts: $posts, " . "xp: $xp, next lvl: $next\n"; # rinse, repeat every minute sleep 60; } # wipe the LCD clean $lcd->clear; # reset pins to default state $pi->cleanup; sub button_press { # this is the interrupt handler print "button pressed\n"; $button_presses++; display_xp(); } sub display_xp { # this is the manager for the bottom LCD # row. It'll update things even when the # main program is sleeping in the while() # loop # print XP for 0 and even number of button # presses, and print XP remaining to next level # on odd number of presses $lcd->position(0, 1); if ($button_presses % 2){ $lcd->print("r: $next"); } else { $lcd->print("x: $xp"); } } sub perlmonks { my $url = "http://perlmonks.org/?node_id=789891"; my $page = get $url; my @content = split /\n/, $page; my ($xp, $posts); my $i = 0; for (@content){ if (/Experience:/){ my $line = $i; $line += 2; $xp = $1 if $content[$line] =~ /(\d+)/; } if (/Writeups:/){ my $line = $i; $line += 2; $posts = $1 if $content[$line] =~ />(\d+)/; } $i++; } return ($posts, $xp); }

    Here's the code without all of the comments....

New Monk Discussion
How was perlmonks built?
1 direct reply — Read more / Contribute
by QuillMeantTen
on Aug 25, 2016 at 10:02

    Greetings,
    I am wondering, does perlmonks use an existing framework? How has its architecture been decided? What are the design principles that are still applied to this day and been there since its inception?

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 having an uproarious good time at the Monastery: (7)
As of 2016-08-25 23:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    The best thing I ever won in a lottery was:















    Results (363 votes). Check out past polls.