Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

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
Strange bug with map
1 direct reply — Read more / Contribute
by erwan
on Feb 10, 2016 at 18:52

    Hi everyone,

    Can anyone help me understand what happens here:

    version 1:

    map { die "bug before!" if (!defined($_)); } values %{$self->{docs}}; my @docsObservs = map { $_->getObservations() } values %{$self->{docs} +}; map { die "bug after!" if (!defined($_)); } values %{$self->{docs}}; print "ok\n";


    bug after! at .....

    Version 2:

    map { die "bug before!" if (!defined($_)); } values %{$self->{docs}}; my @docsObservs; foreach my $docP (values %{$self->{docs}}) { push(@docsObservs, $docP->getObservations()); } map { die "bug after!" if (!defined($_)); } values %{$self->{docs}}; print "ok\n";



    This is just one part of a quite big program that I'm in the process of debugging, so I certainly still have bugs. But I'm puzzled by the fact that switching from version 1 to version 2 (without any other change) solves the issue. I can happily use version 2 of course, but I can't see what is wrong in the first version and I don't like that ;) Any idea?


foreach loop running too many times...?
2 direct replies — Read more / Contribute
by fasoli
on Feb 10, 2016 at 15:18

    Hello dear monks! I've been driving myself crazy over the code below, I can't figure out how to make it run properly :( The files that I'm trying to match are in the style of AC0001_F00001_S00001.tpr, AC0002_F00002_S00001.tpr, AC0003_F00003_S00001.tpr etc. AC goes from 1 to 50 (so AC0001 to AC0050) and frames go from F00001 to F00020.

    So what I'm doing is: I'm putting all my tpr files in an array, then I match their names and then I want to say "for molecule 1 to 2" and "for frame 1 to 2" -> print what files you are finding. However what happens is that, because of the foreach loop, the script print the files that it finds 6 times in total, which is exactly how many tpr files I have. I have tried closing the foreach loop earlier, before the for loops, but that makes no sense. Is there a syntax error? Or am I using the loops totally wrong?

    #!/usr/bin/perl/ use strict; use warnings; my $tpr = "tpr"; my $id; my $filepath; my $batch; my $number; my $molec; my $frame; my $mdstep; my @tpr; @tpr = `ls *.tpr`; print "Script start \n"; print "\n"; foreach (@tpr) { /(\w{2})(\d{4})_F(\d{5})_S(\d{5})/; $id = "AC"; $molec = $2; $frame = $3; $mdstep = $4; for ($molec=2; $molec<=2; $molec++) { for ($frame=1; $frame<=2; $frame++) { my $molecform = sprintf ("%04d", $molec); my $frameform = sprintf ("%05d", $frame); print "$id${molecform}_F${frameform}_S${mdstep}\.$tpr \n"; } } } # end of loop through tpr files
CGI Help
2 direct replies — Read more / Contribute
by phizymonk
on Feb 10, 2016 at 13:34

    So I am just getting into CGI using perl, and the last time I posted I had a lot of help to understand hashes and things, so I figured I would ask here.

    print $q->header("text/html"), $q->start_html("Images in $imagedir"), $q->print("These are all the images in the directory");

    with this code snippet $q is set to "new CGI" is this just laying the ground work for the html part of the script that is running? the goal is to make a script that prints all the images in a directory.

    also I am sort of confused by this regex and I think I am confused because we have not used grep before

     grep { /\.(?:gif|jpg)$/i }
Listbox, radio buttons and text box in sub function?
1 direct reply — Read more / Contribute
by Ppeoc
on Feb 10, 2016 at 08:26
    Hi Monks! I am trying to write a sub function that returns values to the main function using TK GUI. I got the listbox working but cant seem to get the text box to return values to the main function. Here is my code,
    sub myListBox{ my @choice1; my $path; my @listbox_items = @_; my $mw = MainWindow->new; $mw->protocol('WM_DELETE_WINDOW',sub{return;}); my $lsb = $mw -> Frame(); $mw->title("Select terms"); my $lb = $mw->Scrolled("Listbox", -scrollbars => "osoe", -height => 200, -width => 400, -selectmode => "multiple", -exportselection =>1)->pack( ); $lb->insert('end', @listbox_items); $lb->pack(-side => "left"); $lb->Button(-text => "Exit", -command => sub{exit; })->pack(-side => "bottom", -fill => 'x'); $mw->Button(-text=>"Select", -command => sub { foreach ($lb->curselection()) { push @choice1, $listbox_items[$_]; } $mw->destroy()}, )->pack(-side => "bottom", -fill => 'x'); my $label = $mw->Label(-text=>"Enter Directory Path:")->pack( ); + my $entry = $mw->Entry()->pack( ); my $localpath = $entry->get(); MainLoop; return @choice1,$localpath; }
    No value is returned for $localpath. The code runs fine for just the listbox. But when I start adding radio buttons and text boxes, the code gets messed up. My idea is to have a listbox in the left, radiobuttons on top right and text box on bottom right. Any help will be highly appreciated.
Error opening file handle within while loop
5 direct replies — Read more / Contribute
by rjc33
on Feb 10, 2016 at 07:28

    Hi Monks,

    I've written a short script which loops through a file, using some information from a specific line to extract a section of the file using an external program. This section (called $mafBlock) is then used in another external program, and it is the output of this program (called m2.gff) that I am interested in. However, each time the loop proceeds the output file m2.gff is overwritten, so I thought one solution would be to try and open this file within the loop, and then print the lines I require to another output file (m2_most-cons.gff). If I do this I get a syntax error for opening this second filehandle, I've tried a few different ways of writing this but none seem to work. My code is:

    use warnings; use strict; my $maf = "input.maf"; open (IN1, "input.maf") or die; open (OUT1, ">m2.maf") or die; open (OUT2, ">m2_most-cons.gff") or die; while (my $line1 = <IN1>) { chomp $line1; if ($line1 =~ /^s\sficAlb2/) { my @columns = split(/\t/, $line1); my $start = $columns[2] + 1; my $end = $columns[2] + $columns[3]; my $chrom = $columns[1]; my $mafBlock = qx(maf_parse --start $start --end $end $maf); print OUT1 "$mafBlock1\n"; my $phastCons = qx(phastCons --target-coverage 0.3 --expected- +length 45 --rho 0.31 --most-conserved m2.gff --seqname $chrom --msa-f +ormat MAF m2.maf nonconserved-all-4d.mod); print "$phastCons\n" open (IN2, "m2.gff") or die; while (my $line2 = <IN2>) { if ($line2 =~ /^fic/) { print OUT2 "$line2\n"; } } } open (OUT1, ">m2.maf") or die; close IN2; } close IN1; close OUT1; close OUT2; exit;

    Apologies if this is something completely wrong, I'm new to coding and this seemed the most intuitive way to collect the output required.

    Many thanks in advance!
Special character in authorization_basic
1 direct reply — Read more / Contribute
by balakrishna_bk
on Feb 10, 2016 at 05:49

    Hi, I have special character '<' in my password and I get error when i try to login. I tried the following options to encode my password, but still fails

    1. add '\' in front of '<' in password 2. passing username and password in url https://username:'pass<1234'' 3. used uri_escape from URI::Escape uri_escape($pwd) 4. encoded using base64 $r->header( "Content-Type" => "application/soap+xml;charset=UTF-8", "S +OAPAction" => "", "Authorization" => "Basic U1BDX1NJVEUyNFg3OjNmUlRMb +2NjQmZmWHk=" ); sub do_webservice { my ( $weburl, $usr, $password, $webxml ) = @_; print FD "\nXML: \n$webxml\n"; print FD "\nURL: \n$weburl\n"; my $ua = LWP::UserAgent->new(); $ua->ssl_opts( verify_hostnames => 0 ); my $r = HTTP::Request->new( "POST", $weburl ) or warn "POST FAIL +ED:$!\n";; $r->header( "Content-Type" => "application/soap+xml;charset=UTF- +8", "SOAPAction" => "" ); $r->authorization_basic( $usr, $password ); $r->content($webxml); my $response = $ua->request($r); print FD "START Dumper of $response\n"; print FD Dumper $response; print FD "END Dumper of $response\n"; print FD "DEBUG: Response is $response \n"; return $response; }

    Any help is appreciated. Regards, Bala

Problem reading Excel File
3 direct replies — Read more / Contribute
by gunther_maier
on Feb 10, 2016 at 05:44
    Dear Monks,
    I would appreciate help with the following problem:


    I download some data via a weblink, which in my web browser I can either save as XLSX-file or open in Excel. In the latter case, the file opens in protected view and I need to click the button "Enable Editing".

    What I want to do:

    I want to download this file and extract some information from it all in a Perl script. I have mastered downloading with the help of LWP::Simple, but cannot find a way to read the information from the Excel file without manually opening it, clicking "Enable Editing" and saving it again. Once this is done, I can read the content without problems with Spreadsheet::XLSX.

    Many thanks
    Gunther Maier

Progress bar in Tk
2 direct replies — Read more / Contribute
by Anonymous Monk
on Feb 10, 2016 at 03:12

    I have the following code as an example but can't seem to figure out how to use it in my code. In my code I read 5,000+ folders in a file and then parse them and write the results of those files to another directory file by file. I'd like to use the progress bar included here in the subroutine in my script but I don't know where to put the call backs to track time. In this example below they just use a loop and count down. I can do that but it won't be an accurate representation to track with I'm doing.

    #!/usr/bin/perl # a nearly trivial script to mount /mnt/camera on # dev/ttyUSB1, create a target dir, and copy pics # from camera to dir. # Note that mount stuff has been excised for brevity. #--------------------------------------------------------------------- $| = 1; use strict; use Tk; use Tk::Pane; use Tk::ProgressBar; my $message = 'Ready'; my $main = MainWindow->new(); $main->configure(-title=>'Camera 2 Disk', -background =>'blue'); $main->geometry('370x200+100+00'); my $label = $main->Label(-text =>"Digital Camera Tool\nCopy Images fro +m Fuji FinePix to Disk", -relief => 'raised', -background =>'#42b4b4') ->pack(-side=>'top', -fill =>'both'); my $button_frame = $main->Frame(-relief=>'raised') ->pack(-side => 'top', -fill => 'x'); my $dump = $button_frame->Button(-text => 'Dump', -command => \&get_files) ->pack(-side =>'left', -anchor => 'w'); my $status_text = 'Ready'; my $status_label = $button_frame->Label( #-textvariable =>\$status_text, -relief => 'raised', -background =>'grey77') ->pack(-side=>'left',-fill=>'both', -expand=>'1'); my $exit = $button_frame->Button(-text => 'Exit', -command => 'exit') ->pack(-side =>'right'); my $status = $main->Scrolled('Pane', -scrollbars => 'se', -relief => ' +flat') ->pack(-side=>'top', -fill=>'both', -expand=>'y'); #$status->Label(textvariable =>\$message, #-relief => 'flat'); #->pack(-side=>'top', -fill =>'both'); my $percent_done; my $position = '0'; my $progress = $main->ProgressBar(-troughcolor => 'grey70', -width => 20, -length => 370, -anchor => 'w', -from => 0, -to => 100, -blocks => 0.1, -colors => [0, 'blue', 100], )->pack(-side=>'left', -fill=>'both'); $progress->value($position); MainLoop(); #--------------------------------------------------------------------- sub get_files { my $i; while ($i <= 10 ) { $percent_done = int(($i/10) * 100); $progress->value($percent_done); $progress->update; $i++; sleep(1); $message = "Loop number $i."; } }
Regex: Asterisk with NO preceding token
1 direct reply — Read more / Contribute
by pedrete
on Feb 10, 2016 at 03:09
    Hi Monks...!!

    i have "silly"? question for you, please....

    in Perl regex... what is the behaviour of an asterisk with no preceding token????

    an example of my doubt:

    .* matches  
    ok so far...



    *  also matches!!!!!!!!!

How to cut the directory path?
3 direct replies — Read more / Contribute
by aca
on Feb 10, 2016 at 01:56
    Hi, I am trying to cut the directory path in the Perl. Here is my code
    my $filespec = "/usr/share/directory/piano_book.mp4";
    How can i cut the first two directories i.e. /usr/share/ and i want only /directory/piano_book.mp4? Any help will be appreciated. Thanks in advance.

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!
  • 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?

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

    How do I use this? | Other CB clients
    Other Users?
    Others imbibing at the Monastery: (8)
    As of 2016-02-11 03:25 GMT
    Find Nodes?
      Voting Booth?

      How many photographs, souvenirs, artworks, trophies or other decorative objects are displayed in your home?

      Results (358 votes), past polls