http://www.perlmonks.org?node_id=1044

This section is the place to post your general code offerings -- everything from one-liners to full-blown frameworks and apps.

CUFP's
Raspberry Pi GPIO with HiPi
No replies — Read more | Post response
by jmlynesjr
on Jun 16, 2020 at 20:37

    A few examples of using the HiPi Raspberry Pi GPIO Distribution

    The HiPi Distribution allows Perl to drive the GPIO pins on a Raspberry Pi. I2C, SPI, LCD, OLED and other devices are also supported. See https://raspberry.znix.com. If you have previously used RPi::WiringPi, the syntax is very similar and porting was easy.

    My test hardware is a prototype radio front panel with 3 LEDs, 2 Pushbuttons, and a rotary encoder. My testing was done on an RPi 3B+. HiPi also supports the RPi 4.

    I am working on a driver for the Adafruit si5351 oscillator breakout board and an integrated script to connect the front panel to the Quisk Software Defined Radio package via a localhost socket.

    hipiblink.pl - Blink a single LED - "Hello World"

    hipiiotest.pl - Blink 3 LEDs, Read 2 switches, Read an encoder

    hipirpidebounce.pl - Debounce 2 switches

    hipipolledencoder.pl - Read an encoder

    hipicpustats.pl - Display cpu%, Memory%, temperature

    hipiquiskinstallation.txt - Installation notes

    James

    There's never enough time to do it right, but always enough time to do it over...

The 15 Puzzle
5 direct replies — Read more / Contribute
by msh210
on Jun 09, 2020 at 19:48

    Hi, Monks.

    I'm no great shakes at writing Perl but someone threw down the "write the 15 Puzzle" gauntlet (elsewhere) so I decided to try my hand — and I managed to produce my first-ever Perl game (or puzzle). (Of course, the 15 Puzzle has been done before but I wrote my (much simpler) version without reference to that and, heck, I'm proud of it, so give a nonexpert a break. That said, any constructive feedback would be most welcome.)

Shrink Images and PDFs
3 direct replies — Read more / Contribute
by haukex
on May 02, 2020 at 04:53

    Here's a script I use all the time via the right-click menu in my file manager (Nautilus), it will shrink PDFs and images so they work better as email attachments (Update: to be a little more specific: files that are several MB or more are usually due to high-resolution images, so this script runs commands to reduce their resolution). It does require Path::Class, ImageMagick's convert, GhostScript's gs, and my modules IPC::Run3::Shell and Shell::Tools.

    (Also, not Perl related, but I use this pretty much every day: setting up a keyboard combination such as Ctrl+Shift+F for the shell command xsel -b | xsel -ib, which causes the current clipboard buffer to be converted to text-only, which has been incredibly useful when copying formatted text that I don't want to keep the formatting of. The shell command may need to be placed into a simple script file depending on whether you can configure keyboard shortcuts to run a shell command, or if they can only run a single executable.)

    My 3000th node! :-O

Applied MCE : Building a load-testing framework for PSGI apps with Plack::Test and MCE::Queue
No replies — Read more | Post response
by 1nickt
on Mar 30, 2020 at 10:49

    If you develop PSGI apps in Dancer2, Mojolicious, Plack or something else, you probably know that it's fairly easy to test all your routes and confirm that they function as expected. But what about the performance of your app under load? Will there be any bottlenecks? Can the database support the concurrent connections you plan to open? Do you have enough, or too many, workers serving requests? Etc.

    The following script shows how to build a load-testing framework for your PSGI app using Plack::Test for the scaffold and MCE::Flow and MCE::Queue to create the concurrent traffic. (The example includes a Dancer2 app to be exercised, but you can of course use your own app class from outside or inside the script, updating the test flow appropriately.)

    The demonstration simulates an API for managing account records that exposes three endpoints: / POST, / GET, / PUT. The workflow/account lifespan is typical: the caller first creates an account record via a POST call, which returns an id that must be used for future calls. The demonstration simulates the caller encountering the account record still with status 'pending' on the first GET call, and having to call again until it is activated. Finally, the caller deletes the account.

    The script is configured to create 1,000 accounts shared among 10 users. (Note that this is an example and includes no parameter checking, error handling, etc. For demonstration purposes only.) The example app creates an SQLite database on disk.

    How it works
    The script uses MCE::Flow to simulate the workflow, and MCE::Queue to manage the jobs. Two user subroutines are defined, one for the queue "producer" and one for the queue "consumers." The "producer" represents callers making the initial requests to create new accounts; these are placed onto the queue at small intervals. The "consumers" of the queue represent callers making subsequent requests to the app and reacting to the response, sometimes by making a new request. In that case a job for the new request is placed on the queue before the "consumer" finishes the current job.

    To tune the test, change the number of consumers, add more accounts to be created, or reduce/increase the sleeps representing work being performed and caller latency.

    To run the test
    Just copy the code, install the dependencies, and run. You may wish to tail the log file (by default at /tmp/test.log) to see what the app is doing. Afterwards you may wish to examine the populated database (by default at /tmp/test.sqlite), as it will be overwritten on the next run.



    script to load-test/profile a PSGI application


    Some sample output:


    The way forward always starts with a minimal test.
Statistics::Covid : module for fetching and storing covid19-related data for analysis
2 direct replies — Read more / Contribute
by bliako
on Mar 26, 2020 at 15:42

    Fellow Monks,

    I have just submitted to CPAN a very alpha release of a module which collects data from various online providers of Covid19-related statistics (e.g. number of confirmed cases etc.). For example, data provided by Johns Hopkins University (as an arcgis "dashboard") or the data provided by the UK government for data relating to the UK local authorities.

    All the providers I used (so far, John Hopkins University and the UK government) offer an API which provides JSON data. The scraper can be easily configured (that is subclassed) to set the url entry point to the API and how data should be converted to a Perl object. So, it is relatively easy to create more data fetchers which can all store to the same db.

    Fetched data is stored in an SQLite database (support for MySQL exists but remains untested and probably broken - but easily fixed) and there is a high-level interface (thank you DBIx::Class) for saving and retrieving this data. This makes it easy to save data points only if they are more "up-to-date" than what currently exists in database, for the same location and time point (using heuristics). Or, it allows to retrieve all data for a single location over time, or for a single time point/range over all or some locations.

    The CPAN module is Statistics::Covid. It is also hosted on github at https://github.com/hadjiprocopis/statistics-covid which additionally provides the data I have so far collected since a couple of weeks ago.

    If anyone has any comments or suggestions please leave me a message.

    If anyone wishes to contribute, e.g. data analysis or plots generation, under this or any other namespace, please let me know so that I link to that work. I am also starting to write my own analysis which will be under the namespace: Statistics::Covid::Analysis.

    Here is some code from the synopsis as a quick start:

    use Statistics::Covid; use Statistics::Covid::Datum; $covid = Statistics::Covid->new({ 'config-file' => 't/example-config.json', 'providers' => ['UK::BBC', 'UK::GOVUK', 'World::JHU'], 'save-to-file' => 1, 'save-to-db' => 1, 'debug' => 2, }) or die "Statistics::Covid->new() failed"; # fetch all the data available (posibly json), process it, # create Datum objects, store it in DB and return an array # of the Datum objects just fetched (and not what is already in D +B). my $newobjs = $covid->fetch_and_store(); print $_->toString() for (@$newobjs); print "Confirmed cases for ".$_->name() ." on ".$_->date() ." are: ".$_->confirmed() ."\n" for (@$newobjs); my $someObjs = $covid->select_datums_from_db({ 'conditions' => { belongsto=>'UK', name=>'Hackney' } }); print "Confirmed cases for ".$_->name() ." on ".$_->date() ." are: ".$_->confirmed() ."\n" for (@$someObjs); # or for a single place (this sub sorts results wrt publication ti +me) my $timelineObjs = $covid->select_datums_from_db_for_location('Hac +kney'); for my $anobj (@$timelineObjs){ print $anobj->toString()."\n"; } print "datum rows in DB: ".$covid->db_count_datums()."\n"

    Edit: thank yous to marto for advice on githubbing this module and to erix for pointing some errors in this page (John -> Johns)

    BW, bliako

Logging Serial Ports with Mojolicious
No replies — Read more | Post response
by haukex
on Mar 19, 2020 at 16:37

    I gave a talk recently at the German Perl Workshop in Erlangen (video here, in German). In that talk, among other things, I spoke about how I built a data logger for a sensor, and was doing everything with Mojolicious - reading the serial port, logging the data, and providing a user interface. Since it may be a little bit until I can publish the design of the data logger, I've put together a stripped-down example in case it's useful to someone. The key pieces here are:

    It's a relatively long piece of code, but it's entirely self-contained. If you have any questions or suggestions, please feel free to let me know!

    To run this code, first start the second script (e.g. perl fakeports.pl), and then the first, e.g. via morbo serlogger.pl, and then visit the URL shown in the console. (Note this won't work on Windows.)

Export (extract) Mozilla Firefox Bookmarks
No replies — Read more | Post response
by jdporter
on Mar 05, 2020 at 12:52

    Probably reinventing the wheel, but...

    (NB: You may need to cpan install DBD::SQLite first.)

    use DBD::SQLite; use strict; use warnings; =pod This program reads a file named places.sqlite which is found somewhere under your folder named Mozilla/Firefox/Profiles You pass the pathname of this file as a command-line argument. This program outputs html. =cut my $dbfile = shift; $dbfile or die "Usage: $0 <path>/places.sqlite \n"; -r $dbfile or die "Unreadable $dbfile\n"; $dbfile =~ /\bplaces\.sqlite$/ or die "File should be places.sqlite\n" +; my $dbh = DBI->connect("dbi:SQLite:dbname=$dbfile","","") or die "Erro +r opening db $dbfile\n"; my $bookmarks = $dbh->selectall_hashref("select * from moz_bookmarks", +'id'); my $places = $dbh->selectall_hashref("select * from moz_places",'id +'); # construct the tree: my $root; for my $b ( values %$bookmarks ) { if ( $b->{parent} ) { my $p = $bookmarks->{ $b->{parent} }; push @{ $p->{children} }, $b; } else # yep, there's exactly one. { $root = $b; } } # produce the html: local($,,$\)=("\t","\n"); sub walk; sub walk { my $depth = shift; my $n = shift; my $indent = "\t" x $depth; if ( $n->{type} == 2 ) # folder { print $indent . ($depth?"<li>":'') . "<h4>$n->{title}</h4>"; if ( $n->{children} ) { print $indent . "<ol>"; for my $c ( sort { $a->{position} <=> $b->{position} } @{ +$n->{children} } ) { walk($depth+1,$c); } print $indent . "</ol>"; } $depth and print $indent . "</li>"; } else # leaf bookmark { my $link = $n->{title}; if ( $n->{fk} and $places->{$n->{fk}} and $places->{$n->{fk}}{ +url} ) { my $url = $places->{$n->{fk}}{url}; $link =~ /\S/ or $link = $url; $link = qq(<a href="$url">$link</a>); } else { $link =~ /\S/ or $link = "$n->{type}:$n->{id}"; } print $indent . "<li>$link</li>"; } } walk(0,$root);
Get network information from supplied IPv4 address & netmask
2 direct replies — Read more / Contribute
by johngg
on Mar 03, 2020 at 10:55

    I expect there are plenty of tools out there to do this but I had to resort to paper and pencil after someone unplugged the wrong wires in a datacentre ... not me I hasten to add! A script to do the job was called for, especially as I worked in a closed environment where getting any bought-in application approved was a labour of Hercules. This is a tidied up version of the original which might be useful to someone out there.

    Some example usage.

    I hope this is of interest.

    Cheers,

    JohnGG

Announcing Perl-based automation of Notepad++
2 direct replies — Read more / Contribute
by pryrt
on Feb 22, 2020 at 14:35

    Here is my Perl module for automating Notepad++ (the Windows-based text editor). edit: as new versions are released, I will update the VERSION HISTORY, and post a reply so something ends up in Newest Nodes / Recently Active Threads


    NAME

    Win32::Mechanize::NotepadPlusPlus - Automate the Windows application Notepad++

    SYNOPSIS

    use Win32::Mechanize::NotepadPlusPlus ':main'; my $npp = notepad(); # main application

    DESCRIPTION

    Automate the Windows application Notepad++. This is inspired by the Notepad++ plugin PythonScript, but I decided to automate the application from the outside, rather than from inside a Notepad++ plugin. But this module uses similar naming conventions and interface to the PythonScript plugin.

    LIMITATIONS

    This is the first public release of the module. In general, it works. As with all first releases, there is room for improvement; I welcome feedback.

    The first known limitation is that none of the hooks for Scintilla or Notepad++ callbacks have been enabled. That may come sometime in the future.

    All the testing and development was done with a US-English installation of Notepad++, and all the file encodings have been ANSI or UTF-8. I know that I need to include better tests for encoding, and any help you can provide with that is appreciated.

    Notepad++ is a Windows application, so that's the intended platform for this module. However, I know Notepad++ can be made to run in Wine and similar environments in Linux, so it may be possible to make this module drive Notepad++ in such an environment. Feedback on this process is welcome.

    INSTALLATION

    To install this module, use your favorite CPAN client.

    For a manual install, type the following:

    perl Makefile.PL make make test make install

    (You may need to use "dmake" or "gmake" instead of "make", depending on your setup.)

    AUTHOR

    Peter C. Jones

    Please report any bugs or feature requests thru the repository's interface at https://github.com/pryrt/Win32-Mechanize-NotepadPlusPlus/issues, or by emailing <bug-Win32-Mechanize-NotepadPlusPlus AT rt.cpan.org> or thru the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Win32-Mechanize-NotepadPlusPlus.

    COPYRIGHT

    Copyright (C) 2019,2020 Peter C. Jones

    LICENSE

    This program is free software; you can redistribute it and/or modify it under the terms of either: the GNU General Public License as published by the Free Software Foundation; or the Artistic License. See http://dev.perl.org/licenses/ for more information.


    VERSION HISTORY

    2020 Mar 21: v0.002 released to CPAN

    • Reorganize the hash variables for easier and clearer use going forward (#13)
    • editor->getLine() on an empty line will now correctly return an empty string, not "\0" (fixed #14)
    • update API for getNumberOpenFiles to correctly use the constants (#17)
    • add notepad->getNppVar() for accessing the "user variables", like FULL_CURRENT_PATH and CURRENT_WORD (#19)
    • improve documentation internal links (#20)
    • make the editor->hwnd() a public method (instead of using editor()->{_hwnd})
    • make the notepad->hwnd() a public method (instead of using notepad()->{_hwnd})
    • add helper editor->getEOLString(): convert EOL Mode integer to a string
    • editor->getFileEndPosition(): gives the end position of the whole document
    • improve test coverage: add encoding names and getLanguageName coverage to npp-buffer.t
    • examples/ folder: adding more example usages
    • improve Editor documentation on ->findText and some other methods, and clean up set/get pairs, so they share the same information
    • improve Notepad documentation, especially fixing the link for menuCmdID source file


    2020 Apr 6: v0.003 released to CPAN

    The user-centric changes that were made:

    • some of the Scintilla v4.2.0 messages that were implemented in Notepad++ v7.8 were missing, so add them (#29: thanks VinsWorldcom for pointing this out!)
    • runPluginsCommand() = fixed command cache feature and improved test (#30)
    • added version notes, to say which messages and "enums" (hashes/keys) require NPP v7.8 (because these are the Scintilla v4.2.0 updates)
Alternating Case Regex
1 direct reply — Read more / Contribute
by QM
on Dec 14, 2019 at 13:44
    Elsewhere I saw a question asking about matching alternating case strings. Here's the regex, and a test script.
    m/^([a-z]([A-Z][a-z])*[A-Z]?|[A-Z]([a-z][A-Z])*[a-z]?)$/

    It looks a bit clunky, but it works.

    Here's the test script:

    #!/usr/bin/env perl # Test for alternating case regex use strict; use warnings; # Generate all lower/upper combos up to 5 characters with the characte +rs A-E my @test_strings = qw( a A ab aB Ab AB abc aBc Abc ABc abC aBC AbC ABC abcd aBcd Abcd ABcd abCd aBCd AbCd ABCd abcD aBcD AbcD ABcD abCD aBCD AbCD ABCD abcde aBcde Abcde ABcde abCde aBCde AbCde ABCde abcDe aBcDe AbcDe ABcDe abCDe aBCDe AbCDe ABCDe abcdE aBcdE AbcdE ABcdE abCdE aBCdE AbCdE ABCdE abcDE aBcDE AbcDE ABcDE abCDE aBCDE AbCDE ABCDE ); # test all strings, save them in a hash for sorting later my %results; for my $test (@test_strings) { my $result = $test =~ m/^([a-z]([A-Z][a-z])*[A-Z]?|[A-Z]([a-z][A-Z +])*[a-z]?)$/; $results{$test} = $result; } # print the results, sorted by result for my $key (sort by_result_or_length_or_alpha keys %results) { printf "%10s %d\n", $key, $results{$key}; } exit; sub by_result_or_length_or_alpha { ($results{$b} <=> $results{$a}) or (length($a) <=> length($b)) or ($b cmp $a) }

    Here's the output:

    a 1 A 1 aB 1 Ab 1 aBc 1 AbC 1 aBcD 1 AbCd 1 aBcDe 1 AbCdE 1 ab 0 AB 0 abc 0 abC 0 aBC 0 Abc 0 ABc 0 ABC 0 abcd 0 abcD 0 abCd 0 abCD 0 aBcd 0 aBCd 0 aBCD 0 Abcd 0 AbcD 0 AbCD 0 ABcd 0 ABcD 0 ABCd 0 ABCD 0 abcde 0 abcdE 0 abcDe 0 abcDE 0 abCde 0 abCdE 0 abCDe 0 abCDE 0 aBcde 0 aBcdE 0 aBcDE 0 aBCde 0 aBCdE 0 aBCDe 0 aBCDE 0 Abcde 0 AbcdE 0 AbcDe 0 AbcDE 0 AbCde 0 AbCDe 0 AbCDE 0 ABcde 0 ABcdE 0 ABcDe 0 ABcDE 0 ABCde 0 ABCdE 0 ABCDe 0 ABCDE 0

    -QM
    --
    Quantum Mechanics: The dreams stuff is made of

TK font control Linux Windows
1 direct reply — Read more / Contribute
by boleary
on Oct 03, 2019 at 09:24

    I've been struggling for a couple of years with the differences between the Linux and Windows versions of my TK based perl tools.
    So one of my TK UIs in windows would fit nicely on a 1920x1080 screen,
    but would expand strangely and overflow the display when opened in Linux.
    It would take me several hours to re-layout the GUI to work with both applications
    It turns out that the main problem was default font sizes.

    The default Linux font was Helvetica 12 for most widgets, and the Windows font is Arial 8.
    Once I figured that out, I looked around for some solutions to controlling the font sizes.
    The Mastering TK books talk about using Xdefaults or TK::CmdLine,
    but I am distributing my tools as wrapped executables and I cannot count on any kind of pre-existing environment

    I finally found this link from the TCL wiki
    https://wiki.tcl-lang.org/page/Changing+all+fonts+in+an+application

    It was close to what I wanted (in TCL-TK ) But I wanted to have a little more control and set all the Label type widgets to use bold text
    and all the entry type widgets with the same font but not bold

    I came up with this solution that I wanted to share (and be able to search for later) I wrote a sub to defined the default fonts for my application
    and then I call that sub immediately after creating my MainWindow

    #main application our $MAIN_WINDOW=MainWindow->new; #make call here to init the fonts from the very beginning &init_mw_fonts($ctlRef,$MAIN_WINDOW); $MAIN_WINDOW->title("CadEnhance:Part Builder Schematic Symbol Creator" +); $MAIN_WINDOW->configure(-menu=>my $menubar=$MAIN_WINDOW->Menu); # # # MainLoop; sub init_mw_fonts{ #set the default font types or all of our widget classes my $ctlRef=shift; my $mw=shift; require allToolCtlVariables; my $boldFont =&my_tk_cfg_vars("BOLD_FONT") || &all_tk_cfg_vars("BOLD +_FONT"); my $normalFont =&my_tk_cfg_vars("NORMAL_FONT") || &all_tk_cfg_vars(" +NORMAL_FONT"); my $textFont =&my_tk_cfg_vars("TEXT_FONT") || &all_tk_cfg_vars("TEXT +_FONT"); #first set ALL fonts to $normalFont $mw->optionAdd("*font",$normalFont); #then we pick and choose the items we want to be bold foreach my $boldClass (qw(Checkbutton Label Listbox Button Menu Menubutton Message Radiobutton Scale + ProgressBar)) { $mw->optionAdd("*$boldClass.font",$boldFont); } #now set the text Font $mw->optionAdd("*Text.font",$textFont); } #This subroutine lets us program the fonts we want to use #and we can create a similar one for each application called #my_tk_cfg_vars which will override the global one sub all_tk_cfg_vars { my $selection=shift; my %gui_vars=( ENTRY_WIDTH=>80, CFG_ENTRY_WIDTH=>40, DT_ENTRY_WIDTH=>98, TEXT_WIDTH=>110, BACK_GROUND_COLOR=>"light grey", YPAD_SMALL=>0.5, YPAD_MED=>1.0, YPAD_LARGE=>5.0, XPAD_SMALL=>0.5, XPAD_MED=>1.25, XPAD_LARGE=>15, LABEL_FONT=>"Arial 9 bold", BOLD_FONT=>"Arial 9 bold", NORMAL_FONT=>"Arial 9", TEXT_FONT=>"Helvetica 10", ); if (defined ($gui_vars{$selection})) { return $gui_vars{$selection}; } else { return 0; } } sub my_tk_cfg_vars{ my $param=shift; return ""; #or override the values defined in all_tk_cfg_vars }

    Hopefully this may help someone else who might be hitting the same issue

Perl Tk run on Android. It works
1 direct reply — Read more / Contribute
by zentara
on Sep 17, 2019 at 13:46
    Hi,this is a step by step guide, but your experience might differ.

    I am using Android 7.0 Nitrogen on a Nexus 7.

    (1) Go to google play store and install the termux app. Now follow the instructions for setting up a graphical environment at termux gui. I suggest using the tigervnc as the XSDL dosn't work on Android later than v4. Also install the VNC Viewer app. The instructions explain how to setup fluxbox and openbox but I had trouble getting them to load. The default TWM works fine. Basically the commands until now should be "pkg install x11-repo" followed by "pkg install tigervnc aterm"

    (2) Install the cc with "pkg install clang libxorgproto" I found that X11/X.h file was in libxorgproto and is needed.

    (3) While in termux, and at the prompt "pkg install mc" to naviagte and edit :-). Create and edit the file ~/.bashrc and add export DISPLAY=":1"

    (4) Edit the ~/.vnc/xstartup file to say this:
    ##########################
    aterm -geometry 80x24+10+150 -ls &
    twm &
    ###########################

    At the termux prompt, type "vncserver -localhost" and you should get a message saying :1 was started. If not do a "killall Xvnc" and try again. Once you are running, start the VNC Viewer app and enter 127.0.0.1:5901 for address. 5900 + display number

    You should see a black screen in your VNC Viewer with an aterm. In the aterm type "pkg install perl" then "pkg install Tk".

    The Japanese fonts don't seem to work, and the test takes long, but the Tk windows are opening.

    You may find that cpan's install fails at make test, so then just navigate to ~/.cpan/build/Tk-****/ and type "make install". Then you will find that the shebang line #!/usr/bin/perl needs to be symlinked or changed to /data/data/com.termux/files/usr/bin/perl. YMMV. As an easy solution, just start all Tk programs like "perl mytkapp"

    Good luck, have fun. Perl Tk is way easier than Android programming. :-)


    I'm not really a human, but I play one on earth. ..... an animated JAPH
Graphics::Framebuffer + MCE::Hobo and threads
No replies — Read more | Post response
by marioroy
on Sep 09, 2019 at 02:25

    Greetings,

    I'm posting to share something wonderful. MCE and MCE::Shared have reached 1.850. They now work reliably with Graphics::Framebuffer. Three new examples were added to the framebuffer folder on GitHub. Curently, Graphics::Framebuffer works on Linux maybe FreeBSD. The 3 examples many_boxes.pl, many_ellipses.pl, and many_lines.pl use MCE::Hobo, threads (yes this too), and MCE::Child respectively.

    I also updated the PDL demonstration on GitHub, recently. That works on Windows similarly to runing on UNIX.

    Me ka aloha pumehana (kind regards), Mario

simple game of life by new hand
4 direct replies — Read more / Contribute
by glycine
on Sep 08, 2019 at 05:42

    hello! when I first read some things about game of life, it let me amazing. some days ago, suddenly, I find maybe I can make one by my self with perl! although there are a lot of game of life on the internet, wrote by Rust, c++, java... but I think it will be a interesting practice, so I write this :) ( Conway's Game of Life on the Wiki: Conway's Game of Life )

    this code can't be expand to other rules of cell automata, and have a lot of pointless subroutine.

    here is code:

    new: after roboticus give me advice, I change the name of variables and subroutines, delete a bug, so, here is new version.

    I know that using OOP is better, but I am still learning about this, um... I will try it...

    thanks you for read this! p.s., I try to use readmore, but I don't know it if work in preview...

Lexing C++
3 direct replies — Read more / Contribute
by Random_Walk
on Aug 31, 2019 at 19:17

    So folks,

    today I need to makes some sense of C++ files. I will need to parse out function signatures, and I have tried this with regex before, it gets messy especially around templates. Now a similar requirement has reared it's head so step one, lex the code. without further ado here is my attempt at lexing C++. The Lexer is called with an open file handle to a C++ source file. This is lexed into an array of tokens, that is then handed on to the parser.

    What do you think, is this going to give me a nice labeled stream and make parsing a dream, or am I stumbling into know gotchas? Does it qualify as cool?

    Cheers,
    R.

    Pereant, qui ante nos nostra dixerunt!

    Update

    More compiler directives added

Add your CUFP
Title:
CUFP:
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.