Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation

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
simple to describe I/O problem
3 direct replies — Read more / Contribute
by dottornomade
on Sep 01, 2014 at 15:15

    I just can not open some files I received.

    When this simple chunk of code is executed
    use IO::File; my @data; if (-e $file) { print "\nopen $file\n"; } if (my $fh->open("$file, r")) { print "I'm in\n"; @data = <$fh>; $fh->close; }

    something goes wrong. The file is found (message "open filename" is printed, with filename being the correct name of the file), but then I get this error from the I0::File package:

    Can't call method "open" on an undefined value

    In other words, it's like there is no string assigned to the variable $file!

popup_menus retaining values across queries
2 direct replies — Read more / Contribute
by simonz
on Sep 01, 2014 at 08:12

    Hi Monks
    I am creating a popup_menu each time I am fetching a new set of values from the database. But I am running into a problem as default values of popup_menus are retained across queries.
    I am using a conditional statement as below, please help me with a way so that every time it is created the previous values are not maintained.
    I think I am making some syntax error and have to mention it as an array ref but not sure how can I do that while using a conditional statement

    while(defined (my $row = $stmt->fetchrow_hashref)) { my $x = $row->{CONNECTION}; my $y = $row->{CARRY}; my $drop_down = $cgi->popup_menu( -name => "CHOICE", -values => [ 0 .. 6 ], -labels => { 0 => 'NO', 1 => 'A', 2 => 'B', 3=> 'C', 4 => 'D', 5 => 'E', 6 => 'F' }, -default => ($row->{CONNECTION} eq 'Y' && $row->{CARRY}) ? $row->{CARRY}: 0, );

    When the above mechanism did not work, I tried the following one as well i.e taking the decision first in an if-else and then assigning the value but it did not work either :

    while(defined (my $row = $stmt->fetchrow_hashref)) { my $x = $row->{CONNECTION}; my $y = $row->{CARRY}; my $default; if ($x eq 'Y') { if ($y) { $default = $y; } } my $drop_down = $cgi->popup_menu( -name => "CHOICE", -values => [ 0 .. 6 ], -labels => { 0 => 'NO', 1 => 'A', 2 => 'B', 3 => 'C', 4 => 'D', 5 => 'E', 6 => 'F' }, -default => $default, );
Gtk3::Clipboard problem
3 direct replies — Read more / Contribute
by brilant_blue
on Sep 01, 2014 at 06:10


    I wrote following code (filename is

    #!/usr/bin/env perl use strict; use warnings; use diagnostics; use feature qw(say); use utf8; use Gtk3; use Readonly; Readonly my @LINKS => ( { url => '', title => '', }, { url => '', title => 'Google', }, { url => '', title => 'Next URL', }, ); # Links to display Readonly my %CONST => ( WINDOW_TITLE => 'Clipboard', WINDOW_BORDER_WIDTH => 10, WINDOW_WIDTH => 500, WINDOW_HEIGHT => 300, SPACING => 10, # All these numbers are in pixels ); # Some constants for better understanding Gtk3->init; # Initialize Gtk3 my $window = Gtk3::Window->new('toplevel'); my $scrolledwin = Gtk3::ScrolledWindow->new(undef, undef); my $pressed_ctrl = 0; my $store = Gtk3::ListStore->new('Glib::String', 'Glib::String' +); my $view = Gtk3::TreeView->new; my $renderer = Gtk3::CellRendererText->new; my $vbox_main = Gtk3::Box->new('vertical', $CONST{SPACING}); my $hbox_bla = Gtk3::Box->new('horizontal', $CONST{SPACING}); my $button_copy = Gtk3::Button->new; my $column; my $iter; for my $item (@LINKS) { $iter = $store->append; $store->set($iter, 0 => $item->{title}, 1 => $item->{url}); } $view->set_model($store); $column = Gtk3::TreeViewColumn->new_with_attributes( 'Title of page', $renderer, text => 0 ); $view->append_column($column); $column = Gtk3::TreeViewColumn->new_with_attributes( 'URL of page', $renderer, text => 1 ); $view->append_column($column); $scrolledwin->add($view); $button_copy->set_label('Copy URL to clipboard'); $button_copy->signal_connect(clicked => sub { my $selection = $view->get_selection; my @selpaths = $selection->get_selected_rows; for my $tpath ($selpaths[0]) { say '$tpath --> ', $tpath; for my $tp (@$tpath) { say '$tp --> ', $tp; my $iter = $store->get_iter($tp); my $col0content = $store->get($iter, 0); my $col1content = $store->get($iter, 1); say '$col0content --> ', $col0content; say '$col1content --> ', $col1content; my $clipboard = Gtk3::Clipboard->get; # XXX $clipboard->set_text($col1content); } } return; }); $vbox_main->pack_start($scrolledwin, 1, 1, 0); $vbox_main->pack_start($hbox_bla, 0, 0, 0); $hbox_bla->pack_start($button_copy, 0, 0, 0); $window->set_title($CONST{WINDOW_TITLE}); $window->set_border_width($CONST{WINDOW_BORDER_WIDTH}); $window->set_default_size($CONST{WINDOW_WIDTH}, $CONST{WINDOW_HEIGHT}) +; $window->signal_connect(destroy => sub { Gtk3->main_quit; return; }); $window->signal_connect(key_press_event => sub { my $self = shift; my $event = shift; $event = $event->keyval; if ($event == Gtk3::Gdk::KEY_Control_L or $event == Gtk3::Gdk::KEY_Control_R ) { $pressed_ctrl = 1; return; } if ($event == Gtk3::Gdk::KEY_w or $event == Gtk3::Gdk::KEY_q ) { if ($pressed_ctrl) { Gtk3->main_quit; return; } return; } return; }); $window->signal_connect(key_release_event => sub { my $self = shift; my $event = shift; $event = $event->keyval; if ($event == Gtk3::Gdk::KEY_Control_L or $event == Gtk3::Gdk::KEY_Control_R ) { $pressed_ctrl = 0; return; } return; }); $window->add($vbox_main); $window->show_all; Gtk3->main; # Gtk3 main loop

    Output is:

    $ perl $tpath --> ARRAY(0x9f46000) $tp --> Gtk3::TreePath=SCALAR(0x9f45ff0) $col0content --> $col1content --> *** unhandled exception in callback: *** Cannot convert scalar a4a8bf0 to an object of type Gtk3::Gdk::At +om at line 86. *** ignoring at /usr/share/perl5/vendor_perl/ line 321.

    Problem, as you can see in output, is at line 86, marked by '# XXX' at the end of the line.

    What can I do if I want to copy a text in $col1content to clipboard?

add element to hash
2 direct replies — Read more / Contribute
by Anonymous Monk
on Sep 01, 2014 at 03:12
    Hey guys, thank you so far for helping me with some beginner-errors. Now I have another question. I have an Hash, which Looks like this:
    %hash{@key1} => [@array1, @array2, etc]; %hash{@key2} => [@array1, @array2, etc.];
    Now I want to add a string at the end of the elements which belongs to the key. So at the end of the elements of key1, there should be a specific string. like this:
    %hash{@key1} => [@array1, @array2, "abc"]; %hash{@key2} => [@array1, @array2, "abc"];
    I tried it so far with this, but it did not work as expected.
    push (@{$hash{$key}}, (@array1, "abc"));
    I hope someone could help me! Regards sandorado
Child Process as a Function
3 direct replies — Read more / Contribute
by pgduke65
on Aug 31, 2014 at 21:36


    I am looking for guidance regarding a solution to a requirement that I have to run through data and process it in chunks. X number at a time.

    In korn shell, I would release a parenthetical group to the background and have the main program wait for the child processes to complete.

    My initial research has led me to fork/exec. However, all the examples I have seen use a script for the child process. Is it possible to have a function reference execute as the child thread?

    I am also looking for a solution that will run on Windows and Unix. I am assuming that this is possible in PERL?

    Thank you.

filter tcpdump packets
1 direct reply — Read more / Contribute
by syboar
on Aug 31, 2014 at 14:08

    In wireshark we can apply filter packets to find those specific information. Similarly trying in perl to filter tcpdump packets for tcp.options.mss_val == 1430 and print source and destination address. Finding difficult to find tcp options especially from Net::Packet::TCP. Here is the program snippet I'm working on. Checked CPAN module and didn't understand how to obtain tcp options like MSS compare for 1430 and print these source and destination address were MSS match 1430.

    use Net::TcpDumpLog; use NetPacket::IP; use NetPacket::TCP; foreach my $index ($log->indexes) { my ($length_orig, $length_incl, $drops, $secs, $msecs) = $log->heade +r($index); my $data = $log->data($index); my $ip_obj = NetPacket::IP->decode($eth_obj->{data}); next unless $ip_obj->{proto} == NetPacket::IP::IP_PROTO_TCP; my $tcp_obj = NetPacket::TCP->decode($ip_obj->{data}); if (my $packet->{mss_val} eq 1430) { print "\t", $ip_obj->{src_ip}, ":", $tcp_obj->{src_port}, " -> ", $ip_obj->{dest_ip}, ":", $tcp_obj->{dest_port}, "\n"; } }
Combining 2 variable?
6 direct replies — Read more / Contribute
by Krillian
on Aug 31, 2014 at 08:06

    Hi all, Not sure exactly what this is called so cannot find a tutorial. Here is the code:

    $a3 = "Hello"; $b = "a"; $c = "3"; $d = "${$b.$c}"; print $d; # $d should be prints as Hello

    This works fine, but if I change it a little:

    $a[3] = "Hello"; $b = "a"; $c = "[3]"; $d = "${$b.$c}"; print $d; # $d should be prints as Hello

    It no longer works... What am I doing wrong?
    Any help would be very much appreciated and thank you very much in advance!

Strawberry cpan install modules
3 direct replies — Read more / Contribute
by Anonymous Monk
on Aug 30, 2014 at 13:59

    I use Strawberry Perl (Portable) and I'd like to install some extra modules from CPAN. I just use the command "cpan MODULE NAME", and it works fine. But por some modules, I get an error message saying the module is unknown.

    This happens for example with Tk::SplitFrame which is surely in Cpan

    Why it is so?

Confusion with finding strings in command output
2 direct replies — Read more / Contribute
by pgduke65
on Aug 30, 2014 at 13:15


    I have a situation in which I want to search command output for lines containing any of a specified list of strings. I have scoured the net, Perl docs, and written the code below that is still not working. Can someone please help me understand where I am going wrong?

    use constant { TRUE => 1, FALSE => 0 }; our $SUCCESS = 0; our %ErrorStrings = ( "No such file or directory" => TRUE, "does not exist in file" => TRUE, ); # Run command. @Output = qx { command here 2>&1 }; $RetCode1=$?; # If the return was success, we need to scan the output for errors. if ($RetCode1 == $SUCCESS) { # Scan the output and build a list of errors. my @FileErrors = grep { exists $ErrorStrings{$_} } @Output; if (@FileErrors) { $RetCode1 = scalar(@FileErrors); printf "Errors found: [%d] ", $RetCode1; push (@ProcErrors, @FileErrors); } # Non success error code. } else { printf "Error Code: [%d] ", $RetCode1; } # Output a status. printf "%-15s\n", ($RetCode1 == 0) ? "SUCCESS":"FAILED";

    Which produces:

    Processing A_Ra -> A/R ... SUCCESS Processing ADDRESS -> ADDRESS ... SUCCESS Processing ADJ-HIST -> ADJ-HIST ... SUCCESS Processing ALT-PN -> ALT-PN ... SUCCESS Processing AR-LEDGER -> AR-LEDGER ... SUCCESS Processing AR_LEVEL -> AR/LEVEL ... SUCCESS Processing BCBI -> BCBI ... SUCCESS Processing BID -> BID ... SUCCESS Processing BUDGET -> BUDGET ... SUCCESS Processing BUDGET_HEADER -> BUDGET/HEADER ... SUCCESS

    And I have intentionally introduced an error into the command being called. What's more, the output of the command with the error is below:

    'XORDER' does not exist in file. Open file error.

    Please help me understand what I am doing wrong.

    Thank you

Installation failure for Net::Pcap PM
1 direct reply — Read more / Contribute
by waytoperl
on Aug 30, 2014 at 04:49

    Installation failed for Net::Pcap. Warnings mentioned in build.log about not available of list of functions. There are 17 warnings and i'm not able to proceed without installing Net::Pcap, please help.

    ./ warning: "the function pcap_list_datalinks() is not + available" [-W#warnings] #warning "the function pcap_list_datalinks() is not available"
    ./ warning: "the function pcap_createsrcstr() is not a +vailable" [-W#warnings] #warning "the function pcap_createsrcstr() is not available"
    17 warnings generated. rm -f blib/arch/auto/Net/Pcap/Pcap.bundle LD_RUN_PATH="/usr/lib" env MACOSX_DEPLOYMENT_TARGET=10.3 cc -bundle - +undefined dynamic_lookup -fstack-protector Pcap.o -o blib/arch/auto/ +Net/Pcap/Pcap.bundle \ -lpcap \ chmod 755 blib/arch/auto/Net/Pcap/Pcap.bundle /Users/....../perl5/perlbrew/perls/perl-5.20.0/bin/perl -MExtUtils::Co +mmand::MM -e 'cp_nonempty' -- blib/arch/auto/Net/Pcap/ + 644 cp bin/pcapinfo blib/script/pcapinfo /Users/....../perl5/perlbrew/perls/perl-5.20.0/bin/perl -MExtUtils::MY + -e 'MY->fixin(shift)' -- blib/script/pcapinfo Manifying blib/man1/pcapinfo.1 Manifying blib/man3/Net::Pcap.3 Running Mkbootstrap for Net::Pcap () chmod 644 PERL_DL_NONLAZY=1 /Users/......../perl5/perlbrew/perls/perl-5.20.0/bin +/perl "-MExtUtils::Command::MM" "-MTest::Harness" "-e" "undef *Test:: +Harness::Switches; test_harness(0, 'blib/lib', 'blib/arch')" t/*.t # Testing Net::Pcap 0.17 (libpcap version 1.3.0 - Apple version 41) un +der Perl 5.020000

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.
  • 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 rifling through the Monastery: (6)
    As of 2014-09-01 22:16 GMT
    Find Nodes?
      Voting Booth?

      My favorite cookbook is:

      Results (17 votes), past polls