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

ww's scratchpad

by ww (Bishop)
on Aug 25, 2004 at 16:48 UTC ( #385740=scratchpad: print w/ replies, xml ) Need Help??

  • Maybe some fellow monk can fill me in on how to use the int-function, with which perl cuts the decimals of a floating point number. Let me phrase my specific question as a debugger meditation: (perl -d -e 1, which explains, why there are no ";" between the commands)

                $i = 1.255
                $j = $i * 100 + 0.5
                $j = $j * 10000000
                <p>
    
                print $j
                <p>
                ->  1260000000
                <p>
    
                print int ( $j )
                <p>
                ->  1259999999
    			

    Is there a way to make perl behave as a humble user of arithmetics would have expected, without needing additional modules like Math::Round?

  • Hi all, What is the most efficient way (performance-wise,memory-wise) to open a file and putting it into a scalar variable for printing? I'm returning it in a function call so it needs to be in a variable.

  • hi, am new to perl. am working on counting number of syn+ack packets from a machine. though the source and destination is being displayed correctly, the problem lies in counting them. i would be grateful to get some amount of help on this...

    my code is given below:

    
                use Net::Pcap;
                use NetPacket::Ethernet;
                use NetPacket::IP;
                use NetPacket::TCP;
                use strict;
    
                my $err;
    
                #   Use network device passed in program arguments or if no
                #   argument is passed, determine an appropriate network
                #   device for packet sniffing using the
                #   Net::Pcap::lookupdev method
    
                my $dev = $ARGV[0];
                unless (defined $dev) {
                $dev = Net::Pcap::lookupdev(\$err);
                if (defined $err) {
                die 'Unable to determine network device for monitoring - ', $e
                +rr;
                }
                }
    
                #   Look up network address information about network
                #   device using Net::Pcap::lookupnet - This also acts as a
                #   check on bogus network device arguments that may be
                #   passed to the program as an argument
    
                my ($address, $netmask);
                if (Net::Pcap::lookupnet($dev, \$address, \$netmask, \$err)) {
                die 'Unable to look up device information for ', $dev, ' - ', $err
    
                +;
                }
    
                #   Create packet capture object on device
    
                my $object;
                $object = Net::Pcap::open_live($dev, 1500, 0, 0, \$err);
                unless (defined $object) {
                die 'Unable to create packet capture on device ', $dev, ' - ', $er
                +r;
                }
    
                #   Compile and set packet filter for packet capture
                #   object - For the capture of TCP packets with the SYN
                #   header flag set directed at the external interface of
                #   the local host, the packet filter of '(dst IP) && (tcp
                #   [13] & 2 != 0)' is used where IP is the IP address of
                #   the external interface of the machine.  For
                #   illustrative purposes, the IP address of 127.0.0.1 is
                #   used in this example.
    
                my $filter;
                Net::Pcap::compile(
                $object,
                \$filter,
                '(src 192.168.11.248) && (tcp[13] & 2 != 0) && (tcp[14] & 2 != 0)'
    
                +,
                0,
                $netmask
                ) && die 'Unable to compile packet capture filter';
                Net::Pcap::setfilter($object, $filter) &&
                die 'Unable to set packet capture filter';
    
                #   Set callback function and initiate packet capture loop
    
                my $count = 0;
                Net::Pcap::loop($object, -1, \&syn_packets, '$count++') ||
                die 'Unable to perform packet capture';
                print "$count";
    
    
                Net::Pcap::close($object);
    
    
                sub syn_packets {
                my ($user_data, $header, $packet) = @_;
    
                #   Strip ethernet encapsulation of captured packet
    
                my $ether_data = NetPacket::Ethernet::strip($packet);
    
                #   Decode contents of TCP/IP packet contained within
                #   captured ethernet packet
    
                my $ip = NetPacket::IP->decode($ether_data);
                my $tcp = NetPacket::TCP->decode($ip->{'data'});
    
                #   Print all out where its coming from and where its
                #   going to!
    
                print
                $ip->{'src_ip'}, ":", $tcp->{'src_port'}, " -> ",
                $ip->{'dest_ip'}, ":", $tcp->{'dest_port'}, "\n";
                }
    			
  • New Meditations

    1. Note:This RFC obsoletes RFC: Tutorial "Introspecting your Moose code using Test Point Callbacks"

      This second iteration incorporates changes, ideas and comments on the first version, as well as further research on the subject to correctly identify the potential value of using this technique.

      The main idea is to give your testing software the ability to "look" inside subroutines for intermediate results at specific places, namely those problematic spots where you tend to leave debug-level messages to diagnose problems, and especially those places where you would tend to leave a $DB::single=1 to remind yourself and others that this is a place to stop and check a local variable, branching decision, side-effect, etc. The idea is inspired in electronic circuit-board Test-Points and I2C tests and auto-diagnostic circuitry.

      Benefits of using this technique include:

      Enhance to your tests with detailed diagnostics: when a test fails, the intermediate results will give much better clues as to why it's failing, without immediately having to dive into the code. Condition tests based on intermediate results: you may want to run further tests, abort the current test, or flag tests to skip based on the intermediate results of any particular test.

      Advanced Auto-Diagnostics: when a test fails, you may decide to re-run the test and force certain conditions inside a sub, whether to give better diagnostics, or to verify/assert the failure based on expertise/experience: "test assertions"

      The proposed Tutorial follows: Read more... (20 kB)

    2. Note:This RFC has been superseded by RFC Using Test-Point Callbacks for Automated Diagnostics in Testing

      Happy new year fellow Monks!

      I'd like to start the new year by clearing out my pending list with PM which starts with a Tutorial I've been meaning to write about a technique I've been using to test Moose code (but can be used actually for any library).

      Anyway, please have a look and see if this makes any sense or have I been re-inventing the wheel here? Maybe there are better or actually more standard "best practice" ways of doing this. Or perhaps this could could make it to a test module of some sort? it's been working well for me and hopefully it may be useful for others as well, and worthy of a Tutorial. Your comments very welcome.

      Update: Moved the RFC here instead of my scratchpad

      Update: Changed the title, and updated the prose using comments and ideas spawned from the discussion below up to 20110102-1600UTC

      Read more... (18 kB)
  • New Monk Discussion

    1. As a tiny improvement in security and as a tiny step along the path of much bigger improvements in security, I will be changing the site so that you will be required to enter your old password in order to change your password.

      I didn't want to just spring this change without warning, as there are probably quite a few people who have forgotten their PerlMonks password because their browser cookie is enough. But, in reality, this improvement shouldn't present much of a problem even for such people.

      If you don't remember your password, then just make sure your e-mail address is up-to-date and request a "I forgot my password" e-mail (What's my password?). Yes, work has already been done to change that to send you a URL that gives you temporary access to change your password without knowing your current password rather than just e-mailing your current password, unencrypted, but that work has not yet been deployed (I hope to have it deployed fairly soon).

      - tye

  • </body> </html> </c>

    20111202 for jdporter: Holders of Unholy Powers should display a random rumour about the powers of the group rotating every day

    For ambrus re docs: "Certain other shadowy groups co-exist with the Cabal... but the less said about HOUP...BoF... etc, the safer you will be" (or similar... or even not so similar, except for tongue-in-cheek-ness?)"

    20090930 for jakobi re your messages:

    jakobi says Re^3: MIME::Lite and Multipart... - is there a know trick to control the line break in <c>? Even mixes of <c> and <pre> failed. <pre> is more paste friendly for things like diff -u, as <c> makes a mess by adding it's own red col1 plus signs to the display... final q: I intend to keep the log lines in pre format in this node: no danger of download/use/reuse ever. Is <c> indeed preferrable for e.g. syslog output sample lines as well?

    I don't know a good *1 workaround to avoid the red plus, but for several reasons, I believe <c> is better:

    • While the "postfix impression" data renders fine when viewing only the part of the thread beginning with your post, it creates problems for anyone viewing from the OP on through the thread. That's because the indent applied to replies; your <pre> tags and the width of your "postfix impression" stretch the browser window and thus require horizontal scrolling to read the narrative (enclosed in <p>...</p> tags). IOW, the pre tags and the length of the data lines bork the display.
    • While the rendering of long data lines wrapped in code tags may satisfy your criteria for "unsightly", any reader who wishes to see them in their original format can do so by using the "download" link that appears below each code block.

    *1 You could, of course, manually reformat the data-lines to 60 or so chars, perhaps indenting each continuation line with multiple spaces pr \t or similar. That would avoid the existing problem -- forcing horizontal scrolling on other posts in the thread -- in some, but not all cases (consider what happens if you're replying to a reply to a reply -- meaning your post will be indented 4x). hth, thanks for your other pre replacements, and cheers. ww

    20090901 for tye

    #!C:\perl\bin use strict; use warnings; # define the table using one anonymous code-ref and one named code-ref my %dispatch = ( "-h" => sub { print "hello from anonymous sub\n"; }, "-g" => \&say_goodbye, "-?" => \&explain, # added +by ww ); sub say_goodbye { print "goodbye from named sub\n"; } sub explain { # added by + ww print "\tPer Wikipedia post, \"When as 'perl greet -h' will produce +'hello',\n\tand running it as 'perl greet -g' will produce 'goodbye'. +\"\n\tBUT when run (with proper association to perl on W32)\n\t\"C:\\ +F:\\pl_test\\dispatchWikip.pl -h\" returns\n\t 'Use of uninitialized +value in hash element at \"F:\\pl_test\\dispatchWikip.pl line 21.\"\n +\t unknown argument\n\tperl -v: This is perl, v5.8.8 built for MSWin3 +2-x86-multi-thread\n\t\t (with 33 registered patches, see perl -V for + more detail)\n"; } # fetch the code ref from the table, and invoke it my $sub = $dispatch{$ARGV[0]}; print $sub ? $sub->() : "unknown argument\n"; =head dispatch table fr Wikipedia, cf (local) dispatch.pl and (PM) #456530 Running this Perl program as perl greet -h will produce "hello", and r +unning it as perl greet -g will produce "goodbye". BUT RETURNS ERROR WHEN RUN C:\ F:\_wo\pl_test\dispatchWikip.pl -h "Use of uninitialized value in hash element at F:\_wo\pl_test\dispatch +Wikip.pl line 21. unknown argument" =cut

    20090210 RFP Acme::Warnings after an idea by moritz

    package Warnings; use strict; use warnings; use Exporter; use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS); $VERSION = 0.02; @ISA = qw(Exporter AutoLoader); @EXPORT = qw(Warn); @EXPORT_OK = qw(Warn); sub Warn { print "\n"; my $j = int(rand(0xff)); my @msg = ("\n\t Viruses found :" . $j . "\n\tViruses infestations cle +aned: " . ($j - 13) . "\n\t", "\n\t Delete all files? Y/N\n\t Y\n\n\t All Files Deleted.\n\t +When you exit, your drive will be ready for reformatting.\n\n\t", 'libXMLS not found.', 'Corrupt file: ' . $0, 'NaN on ' . gmtime(), 'Perl 7 syntax not yet supported.', 'CAUTION: this construct may cause your computer to spit fire.' +, 'Syntax at line ' . int(rand(240)), "Use of term\(\) in list context.", 'Deprecated: see Acme::Bleach', "Ouch! That's really ugly.", 'Unspecified error.', '$inStit not in scope at Line ' . int(rand(71)), , 'Your Perl is borked. Recompile.', 'Useless use of a void in constant context at $0 line 7.', 'Did you forget an opening brace?', "I'm baffled.", ' %hash 0xdf31a45 (Bad RAM?)', 'Perhaps you should downgrade to PHP.', "Any idiot can see that won't compile. \#^~!x-`@\$@**9u~8! ", 'Write protect error reading device CON: ', int(rand(42)) . ' ERRORS suppressed by C<no errors> option.', 'An undeclared %hash name here was an unpleasant shock.', 'Huh?', 'The $hashref is not in scope in this block; Auto::Load must ha +ve messed you up or you may have failed to C<bless> it properly. Furt +her, please note carefully that this message renders too wide for you +r window.', 'Use Paranoia::Now; Did you type "/*" instead of "#" as a pref +ace to what looks like a comment?', 'Too many errors on one line. (Make fewer)', 'Symbol table full - fatal heap error; please install additiona +l RAM.', "Trailing comma not permitted in this function.", 'THE PREVIOUS STATEMENT IS REDUNDANT AND HAS BEEN DELETED.', 'If you made a sufficiently large number of errors, you will re +ceive a large portrait of Alfred E. Neumann.', 'Aaaargh!', 'Module ASM::InLine not found in C<@inc>.', 'Your POD is missing or broken. How am I supposed to know what +to do?', 'UNSAFE! Even C<perl -c fn> may trash your machine.', 'Server Error: No errors found! (Error ID 2966713b20938)', 'Universal pointers may not be dereferenced', '"8, 9, or A - F" in octal number', 'Cannot modify a annoymous constant at Line13', 'Bit error rate', '"Chomp" not supported on 8080 or Z80 CPU under zpr3', 'Unsafe HEX value', 'Unable to locate *foo - Program halted!', 'Cannot read. File is Write-Only.', 'Named capture requires requires CP/M 2.0 or newer version.', 'Baud rate cannot be set for this device.', 'LINK-80 atttempted to write a segment into memory already used + by another segment.', ' ', ); my $i = int(rand($#msg)); my $msg= $msg[$i]; if ( $i == (0) or $i == (1) ) { Scare($msg); } my $script_name = reverse($0); my $script_nam; if ( $script_name =~ m!([^-\ \/: _]*)|[^\.]!g ) { $script_nam = $1; } my $name = rand(ord(localtime())) . ' See also: ' . int(rand(hex(ord( +$script_name)))) . '.42' ; my $flag = (rand(3)); if ( $flag < 0.7 ) { print "\t Error: " . $i . " - $msg\n\t Compilation Terminated\n"; exit; } elsif ( ($flag >= 0.7) && ($flag <2.3) ) { print "\t Warning: $msg\n"; } elsif ( ($flag >= 2.3) && ($flag <2.8) ) { print "\t $msg $name\n"; } elsif ( ($flag >= 2.8) && ($flag <2.9) ) { print "\t No syntactical violations found. However, your script wi +ll B<NOT> do what you wanted.\n"; } else { print "\t COMMENT: $name \n"; } unless ( $flag >=2.8 && $flag <2.9 ) { print "\t Too many uncaught exc +eptions. Compilation aborted\n"; } exit; } sub Scare { my $Smsg = $_[0]; print chr(0x07) x 10; print $Smsg; sleep 3; print "$^O not found.\n\t"; sleep 1; system("L:\tests"); sleep 10; exit; } 1; __END__ =head =head1 NAME Acme_warnings =head1 SYNOPSIS Pure Perl: install as usual or simply copy to /Perl/site/lib/ACME/Warn +ings.pm Simple copy assumed here and below at "Example Script". use ACME::warnings; ... (some code here)... Warnings::Warn(); =head1 DESCRIPTION When use(d) as above, prints a ficticious error, warning or 'COMMENT' (and an occasional 'Congratulations'); then exits. =head1 PARAMETERS none =head1 RETURN none =head1 AUTHOR ww (user id at PerlMonks) =head1 VERSION 0.02 2009-02-16 =head1 ACKNOWLEDGEMENTS moritz (user id Perlmonks) for the idea and contributions to C<@msg>. B<Errors in implementation are ww's alone.> =head1 BUGS: None known (yet). =head1 LICENSE The same as Perl itself. =head1 EXAMPLE SCRIPT: C< #!/usr/bin/perl use strict; use warnings; use ACME::Warnings qw (Warn); print "this is a test\n"; Warnings::Warn(); __END__ > =cut


    The version of "Markup in the Monastery" which was posted here is no longer current; see Markup in the Monastery, 20080318



    post-9/11 Idiocy (Identifying office symbols, names, deleted):

    Effective immediately, due to an INFOCON level increase, Outlook Web Access (OWA), Webmail, has been shutdown. We do not expect that it will be back online anytime soon, if at all. Please remember, this is not a XXXX Automation Helpdesk decision and XXXX can not remedy the situation.

    To access your email remotely, consider the following choices:

    1. Use AKO Webmail (If you still have an Exchange Account on the xx Domain you will not be able to receive email from other users on the xx Domain unless they email you directly from their AKO to your AKO). Make sure you have removed forwarding on your AKO account. This solution should be used for M-Day personnel or temporary travel situations.
    2. Use VPN Access from your Government Laptop. If you need VPN installed, please open a trouble call with the Automation Helpdesk.
    3. Use a Government owned Blackberry, if you have been issued one.

    The HTML capability to send and receive email will also be removed. We are now enforcing plain-text only emails. It will make emails look a little strange and you can not have hyperlinks in the email message. If someone gets all square boxes, instead of text, in an email please open a trouble call with the Automation Helpdesk.

    ** As a further reminder, all users must register their CAC Cards on our Intranet site. Just click on CCL Registration. Accounts that do not have a CAC registered will be deleted. All workstations need to be upgraded to Windows XP. Computers still running Windows 2000 will be cut off from the network. Computers must be brought into the Automation Helpdesk in xxxxxx to have them upgraded to Windows XP.

    xxxxxxxxx, XXX... (name, etc, removed to protect the innocent)

    Gaaaaak! my reply....

    TO:               (Addressees supressed: identification of individuals and 
                       units compromises security)
    
    SUBJECT:          INFOCON
    
    CLASSIFICATION:   Unclass
    
    DATE:             suppressed, just because we can)
    

    Effective yesterday and for the foreseeable future, email has been suspended. An INFOCON level increase, directed by higher authority, required us to take this step. Higher Authority asserts that this step will not only increase security for all members of the United States Military Forces, but will also enhance efficiency, allowing additional resources to be devoted to The War On Terror.

    In the future, and effective immediately, all correspondence, directives, orders and other information previously conveyed by email will be inscribed on "paper" or "vellum" (definitions and explanations, infra., at Note 1.) utilizing any of the following acceptable technologies:

    • a. "Typewriter:" A typewriter is a device similar to a combination of a computer keyboard and printer). See Note 2.
    • b. Pen and ink: Acceptable pens include: goose quill, only. (See Note 3).
    • c. Chisel and stone: Use only for those documents requiring the greatest permanency.

    Also per the current INFOCON level SOP, possession or use in any military workplace of computer-related technology (exceptions at Note 4.) may, at the discretion of whomever (Note 6.) is next assigned to the Helpdesk after the violation is reported, may subject military personnel to disciplinary proceedings up to and including General Court Martial. Civilian personnel will be summarily executed.

    There is one further additional unrelated note, which we have hidden at the bottom of this memo in the expectation that some of you will fail to read it.


    Note 1: "Paper" is a form of material commonly found in the form of sheets and often white in color, and sometimes utilized to disseminate information printed or written thereon. Some Members may have observed or even utilized "paper" in the past. Check with your chain of command for your unit or Directorate Paper-Coordinator. "Vellum" is an obsolete technology whose re-introduction to the military forces will afford our communications contractor the opportunity for vast profit.

    Note 2: Manual typewriters only. Electric typewriters generate decodeable and interceptable radio frequency pulses for each character typed. Current technology is known to allow interception of these pulses at distances up to dozens of millimeters. Further, since an on-going study of potential security hazards has identified power lines as a possible source of information compromise, electric appliances may be proscribed in the future.

    Note 3: As a field expedient, when necessary, crayons may be utilized. Additionally, in the field, documents are permitted, when required, to be inscribed upon birch bark or slabs of newly hewn wood. However, use of cabbage leaves is deprecated.

    Note 4: Qualified Information Technology or Intelligence personnel (cf: oxymoron) are authorized and directed to operate captured Al Quaeda computer technology for the purpose of analysis and tactical data gathering. In addition, use of digital numerical calculators is authorized, when required and on a case-by-case basis, and when specifically approved by appropriate authority (minimum: GS-15 level). Examples of appropriate use include the calculation of artillery aiming and inventory accountability maintenance.

    Note 5: This note left deliberately BLANK. (Well, not really, because it says its blank, but you should get the idea.)

    Note 6: Since the continued contraction of authorized uses of Information Technology is anticipated to accelerate in compliance with the latest INFOCON level change, most assigned IT personnel will be transferred to alternate duties. However, current projections anticipate that at least one IT staff member will be assigned to help desk duties on the third Thursday of months whose (US English) names include the letter "p" or "x."

    Unrelated information: Yesterday has been declared an additional holiday for state and federal personnel who were actually present for and performing duty yesterday. Those individuals are authorized to have taken yesterday off. Employees and Members on a regular day off, pass or leave day or otherwise not present for and performing their customary duties yesterday are NOT authorized an alternate or compensatory day. Additionally, and solely to further obfuscate our intent, here is a second additional bit of information; a key and relevant proviso of the latest INFOCON level SOP: creation or possession of any document, paper, file or other information storage technology utilizing justified type (or, typesetting) will be deemed prima facie evidence of the possession or use of prohibited technology.

    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 avoiding work at the Monastery: (7)
    As of 2015-08-30 23:41 GMT
    Sections?
    Information?
    Find Nodes?
    Leftovers?
      Voting Booth?

      The oldest computer book still on my shelves (or on my digital media) is ...













      Results (351 votes), past polls