BaCon Bits

For discussions about programming, programming questions/advice, and projects that don't really have anything to do with Puppy.
Message
Author
User avatar
GatorDog
Posts: 138
Joined: Tue 12 Sep 2006, 16:43

Bacon port of "resizepfile"

#115 Post by GatorDog »

"resizepfile.sh" is a Puppy script to resize the Puppy save file.
This program is a port of the resizepfile script to a Bacon program.
In particular it makes use of Bacon's Associative array.
An associative array is an array of which the index is determined by a string, instead of a number. Associative arrays use
round brackets '(…)' instead of the square brackets '[…]' used by normal arrays.

An associative array can use any kind of string for the index, and it can have an unlimited amount of elements.

Code: Select all

fullname$("bob") = "Robert Fuller"
fullname$("jane") = "Janet Jenkins"
name$ = "bob"
PRINT fullname$(name$)
Output: Robert Fuller
EDIT: Corrected missing "$" on variable name.

The resizepfile shell script uses an external file (/etc/rc.d/PUPSTATE) to retrieve variables and their values.
The variables are in shell syntax. ie. variable = 'text'. This syntax is decoded and assigned
values in Bacon using an associative array.

This is the contents of (my) /etc/rc.d/PUPSTATE:

Code: Select all

PUPMODE=12
PDEV1='sr1'
DEV1FS='iso9660'
PUPSFS='sda1,vfat,/l5281108.173/lupu_528.sfs'
PUPSAVE='sda1,vfat,/lupusave-528_IM-.3fs'
PMEDIA='cd'
#ATADRIVES is all internal ide/pata/sata drives, excluding optical, excluding usb...
ATADRIVES='sda '
#ATAOPTICALDRIVES is list of non-usb optical drives...
ATAOPTICALDRIVES='sr0 sr1 '
#these directories are unionfs/aufs layers in /initrd...
SAVE_LAYER='/pup_rw'
PUP_LAYER='/pup_ro2'
#The partition that has the lupusave file is mounted here...
PUP_HOME='/mnt/dev_save'
#(in /initrd) ...note, /mnt/home is a link to it.
#this file has extra kernel drivers and firmware...
ZDRV=''
#complete set of modules in the initrd (moved to main f.s.)...
ZDRVINIT='no'
#Partition no. override on boot drive to which session is (or will be) saved...
PSAVEMARK=''
The variable name (ex. PUPMODE) will be used for the associative arrays index (ex. Pupstate$("PUPMODE")
I used a SUB-routine to translate the shell variables. Here is commented code.

Code: Select all

' ------------------
SUB READ_PUPSTATE_VARIABLES
' ------------------
	' Declare the associative array
	DECLARE Pupstate$ ASSOC STRING

	' Open the file for reading
	OPEN Pupstate_file$ FOR READING AS Filehandle_

	' Check for end of file
	WHILE NOT(ENDFILE(Filehandle_)) DO

		' read in line by line
		READLN Pass$ FROM Filehandle_

		' CHOP$ - remove leading/trailing space, tab, CR, etc.
		Pass$ = CHOP$(Pass$)

		' If line begins with "#" it's a comment.
		IF LEFT$(Pass$, 1) = "#" THEN
			'Dump bash comment lines
			CONTINUE
		END IF

		' If line contains "=", there's a variable assignment going on.
		IF INSTR(Pass$, "=") THEN

			' Break line up using "=" as seperator
			' Arg$[1] will be variable name. Arg$[2] is the value.
			SPLIT Pass$ BY "=" TO Arg$ SIZE na

			' Replace the single quotes with null
			Pass$ = CHOP$(REPLACE$(Arg$[2], Single_quote$, ""))

			' Set up variable = value
			Pupstate$(Arg$[1]) = Pass$
		END IF
	WEND
	' Close file
	CLOSE FILE Filehandle_
END SUB
This is a simple use of associative arrays. There are some extended examples in the Bacon reference pages.
The rest of the program implements the actions of the shell script along with the addition of a GUI.

GatorDog
Attachments
resizepfile.png
(36.56 KiB) Downloaded 1147 times
Bacon-resizepfile-src.tar.gz
Bacon source code for resizepfile.bac
(3.64 KiB) Downloaded 509 times
Last edited by GatorDog on Mon 31 Oct 2011, 18:59, edited 1 time in total.

big_bass
Posts: 1740
Joined: Mon 13 Aug 2007, 12:21

#116 Post by big_bass »

Hey GatorDog

thanks for posting that http://www.murga-linux.com/puppy/viewto ... &start=114 (I had already ported the old xmessage resizepfile.sh
to Xdialog and added larger save options) so going over your BaCon version
will be easier for me to understand and follow this new associative array in action
thanks this will be fun to learn in Bacon :D

*I know this is a BaCon thread but only to ease into understanding what is happening
the equivalent bash4 example is given below using your example converted to bash4

GatorDog
# associative array Bacon example
fullname("bob") = "Robert Fuller"
fullname("jane") = "Janet Jenkins"
name = "bob"
echo $fullname($name)


big_bass

Code: Select all

# bash4 associative array equivalence to the Bacon example above

declare -A fullname
#       -A option declares associative array.

fullname[bob]="Robert Fuller"
fullname[jane]="Janet Jenkins"


echo "bob's fullname is ${fullname[bob]}."
echo "jane's fullname is ${fullname[jane]}."

echo "${!fullname[*]}"   # The array indices used
Joe

User avatar
GatorDog
Posts: 138
Joined: Tue 12 Sep 2006, 16:43

#117 Post by GatorDog »

Hi Joe,

To further the comparison a little, LOOKUP is used to get the array indices in Bacon.
(LOOKUP works similar to the SPLIT command)
LOOKUP <assoc> TO <array> SIZE <variable>

Code: Select all

LOOKUP Pupstate$ TO Index_name$ SIZE Count
and to access -

Code: Select all

FOR x = 0 TO Count - 1
    PRINT Index_name$[x]
NEXT 
GatorDog


User avatar
sunburnt
Posts: 5090
Joined: Wed 08 Jun 2005, 23:11
Location: Arizona, U.S.A.

#119 Post by sunburnt »

Hi guys; Thought I`d ask before just doing this in Bash.

My years of Quick Basic are slowly coming back to me as I use BaCon.
I recalled that Basic works with arrays not lists, Bash is powerful with both.
Basic`s problem with arrays is getting data into them... It`s one line at a time.
Bash will read and write files and arrays all in one statement.
I`m going to suggest this for the next BaCon, and also passing arrays to/from Bash.

# The Q:
An easy way to get the number of lines in a file to declare the array index?
All I can think of to do is:

Code: Select all

	OPEN File$ FOR INPUT AS file
	i = -1
	WHILE NOT(ENDFILE(file)) DO
		INCR i
		READLN txt$ FROM file
	WEND
	CLOSE file

	GLOBAL Array$[i] TYPE STRING

	OPEN File$ FOR INPUT AS file
	i = 0
	WHILE NOT(ENDFILE(file)) DO
		READLN txt$ FROM file
		IF ENDFILE(file) THEN BREAK
		Array$[i] = txt$
		INCR i
	WEND
	CLOSE file
Not a very efficient or elegant way to do anything at all.!

seaside
Posts: 934
Joined: Thu 12 Apr 2007, 00:19

#120 Post by seaside »

sunburnt,

Perhaps something like this-

Code: Select all

i$=EXEC$("wc -l filename")
Whether that's faster or not remains to be seen.... :)

regards,
s

User avatar
sunburnt
Posts: 5090
Joined: Wed 08 Jun 2005, 23:11
Location: Arizona, U.S.A.

#121 Post by sunburnt »

seaside; I thought of that, but why bother with BaCon if always using Bash.

Long ago in Quick Basic I noticed the HD cranking with each "read line".
Visual Basic had a second "input" command that would take in the whole file.
I`d like to see BaCon do file I/O and fill arrays quickly in one command.

I thought of just making a BaCon function library to simplify the repetitive code.
But that doesn`t improve BaCon`s actual operation any. It`d still work the HD.

At the moment my thought is porting my Bash app. "sysinfo" to BaCon.
I could do as you suggested, but then why not just have it call sysinfo?
I wrote a wrapper script to redirect sysinfo`s output to a file for BaCon to read.

But BaCon as a wrapper for Bash is sad. What`s the point of a compiled exec.?
For BaCon to be really useful it has to do most code stuff by itself.

User avatar
GatorDog
Posts: 138
Joined: Tue 12 Sep 2006, 16:43

Bacon Associative Arrays

#122 Post by GatorDog »

Sunburnt,
An easy way to get the number of lines in a file to declare the array index?
One way to accomplish the array assignment is to use Associative arrays.
This snipit will give you the line count and also goes ahead and assigns the lines to Array$(....) .

Code: Select all

DECLARE Array$ ASSOC STRING
Array_index = 0
OPEN My_file$ FOR READING AS Filehandle_
WHILE NOT(ENDFILE(Filehandle_)) DO
	INCR Array_index
	READLN Txt$ FROM Filehandle_
	Array$(STR$(Array_index)) = Txt$
WEND
CLOSE FILE Filehandle_
GatorDog

User avatar
vovchik
Posts: 1507
Joined: Tue 24 Oct 2006, 00:02
Location: Ukraine

getting text file into array

#123 Post by vovchik »

Dear sunburnt,

I already posted this in the BaCon forum, but here it is again. Just another way:

Code: Select all

' --------------------
FUNCTION CAT(STRING FILENAME$)
' --------------------
    LOCAL fileline$, txt$ TYPE STRING
    IF FILEEXISTS(FILENAME$) THEN
        OPEN FILENAME$ FOR READING AS catfile
        WHILE NOT(ENDFILE(catfile)) DO
            READLN fileline$ FROM catfile
            txt$ = CONCAT$(txt$, fileline$, NL$)
        WEND
        CLOSE FILE catfile
    END IF
    RETURN CHOP$(txt$)
END FUNCTION

x$ = CAT("myfile.txt")
SPLIT x$ BY NL$ TO myarray$ SIZE mysize
The var "mysize" will be the size of the arrray (i.e. no. of lines). You can use "OPTION COLLAPSE" at the top of your program to ignore empty lines. As for passing arrays to SUBs and FUNCTIONs, Peter explains that business in the first few pages of the BaCon manual. It is entirely possible.

With kind regards,
vovchik

PS. BaCon should not be construed as a bash replacement, but a normal compiled language, like C, but with nicer, easier syntax. If you have complex tasks, it runs circles around bash.

PPS. If it is terseness that you're after, you can always do the following:

Code: Select all

x$ = EXEC$("cat myfile.txt")
SPLIT x$ BY NL$ TO myarray$ SIZE mysize

big_bass
Posts: 1740
Joined: Mon 13 Aug 2007, 12:21

#124 Post by big_bass »

thanks vovchik,GatorDog
for the great code snippets

and thanks for sparking the question sunburnt
I was trying to do arrays in BaCon too
as I was following the presize.bac code GatorDog posted
since I am used to doing this in bash I want to do it in Bacon also

arrays are the easy way to pull out data

*really the whole problem with linux in general is
important files have scrambled un formatted
data that needs much filtering to get the data out into "useable"
data if much pre thought went into those important files
we wouldnt need so many different tools to filter out the data
and everything would be easier and faster
I commented about this in "speeding up bash scripts"
If it is terseness that you're after, you can always do the following:
I like terse and simple and commented :D
I like to recycle simple code snippets sometimes I forget how to
do somethings that appear easy
it takes too much time to read large programs
and take out some small usable pieces because they get too complex
as time goes while new features get added quickly

so here is simple I took vovchik's snippet and added just a little bit to it
to keep it simple and recyclable
Joe

Code: Select all

'--- cat the file into an array using  x$ ---'
x$ = EXEC$("cat /etc/rc.d/PUPSTATE")
SPLIT x$ BY NL$ TO myarray$ SIZE mysize 

'--- this prints all arrays ---'
FOR x = 0 TO mysize  - 1
    PRINT myarray$[x]
NEXT 

'--- this prints only the first array ---'
PRINT myarray$[0]

'--- this prints only the scecond array ---'
PRINT myarray$[1]

'--- this prints only the third array ---'
PRINT myarray$[2]



is there a way to covert this bash snippet to BaCon
to check for undefined arrays

Code: Select all

#str=something

str=""

if [ $str ]
then
	echo "Not empty"
else
	echo "Empty"
fi

now if we only had some regular expressions in Bacon
explained with simple code snippets

I would be so happy it would make me dance

User avatar
GatorDog
Posts: 138
Joined: Tue 12 Sep 2006, 16:43

Bacon regular expressions

#125 Post by GatorDog »

now if we only had some regular expressions in Bacon explained with simple code snippets
Bacon REGEX
This checks that the text does not contain digits.
Then it looks for an underline chr or a capital X.

Code: Select all

Txt$ = "big_bass"

IF REGEX(Txt$, "[^[:digit:]]") THEN
	PRINT "Yep, ", Txt$, " is an ahpha dog!"
END IF

IF REGEX(Txt$, "_|X") THEN
	PRINT "Yes, there IS an underline chr or a capital X."
END IF
I would be so happy it would make me dance
It may not rise to the level of a dance, but can I at least get a toe-tap? :wink:

rod
Attachments
sparky.gif
(498 Bytes) Downloaded 1502 times

User avatar
sunburnt
Posts: 5090
Joined: Wed 08 Jun 2005, 23:11
Location: Arizona, U.S.A.

#126 Post by sunburnt »

Hey Gatordog; I hadn`t noticed the REGEX command, rather useful.!

big_bass; Yep, there`s sooo much parsing in Bash making it very "codey".
You`d think the authors of Linux`s execs. would`ve made raw output modes.
# That`s why I wrote the Bash function library sysinfo, to get raw data.
I`ll be adding more "needed" functions to it, ie: file size, etc. Any suggestions?
Too bad it becomes a dependency, now if scripts like it were std. in Puppy...

vovchik; Excellent.! I didn`t think of using a variable first. Much simpler.!

User avatar
GatorDog
Posts: 138
Joined: Tue 12 Sep 2006, 16:43

#127 Post by GatorDog »

Hey big_bass,
big_bass wrote:is there a way to covert this bash snippet to BaCon to check for undefined arrays

Code: Select all

#str=something

str=""

if [ $str ]
then
   echo "Not empty"
else
   echo "Empty"
fi 
Is this what you're asking for :?:

Code: Select all

str$ = ""

IF LEN( str$ ) THEN
	PRINT "Not empty"
ELSE
	PRINT "Empty"
END IF
GatorDog

User avatar
vovchik
Posts: 1507
Joined: Tue 24 Oct 2006, 00:02
Location: Ukraine

#128 Post by vovchik »

Dear big_bass and GatorDog,

This function works for string arrays:

Code: Select all

' Define runtime check for size of array
DEF FN bound(x) = SIZEOF(x)/SIZEOF(STRING)
It returns the number of elements. As for the bash equivalent to return empty or not for a particular array element, LEN returns "FALSE" if there is nothing there. If there is something in the string, LEN will be "TRUE" in the Boolean sense. GatorDog's example is perfect in that regard.

With kind regards,
vovchik

User avatar
GatorDog
Posts: 138
Joined: Tue 12 Sep 2006, 16:43

#129 Post by GatorDog »

Hey vovchik,

Code: Select all

' Define runtime check for size of array
DEF FN bound(x) = SIZEOF(x)/SIZEOF(STRING)
Could you clarify what is passed in "x" and where "STRING" comes into play?

tnx
GatorDog

User avatar
sunburnt
Posts: 5090
Joined: Wed 08 Jun 2005, 23:11
Location: Arizona, U.S.A.

#130 Post by sunburnt »

vovchik; I think I know what`s going on in your code snip, but tell us anyway...

I agree writing a multimedia codec in BaCon would be much better than Bash.
But so much of what`s done ( or needed ) is system related stuff.
There`s not many full blown applications being written that are new.
Most of what I see is people rewriting and reinventing the wheel.

My sysinfo function library is a good example, nothing new there.
I just wanted "no parsing raw data output" for many things all in one file.

User avatar
vovchik
Posts: 1507
Joined: Tue 24 Oct 2006, 00:02
Location: Ukraine

#131 Post by vovchik »

Dear GatorDog and sunburnt,

This is one example of the "bound" function:

Code: Select all

' Define runtime check for size of array
DEF FN BOUND_STR(x) = SIZEOF(x)/SIZEOF(STRING)
' Create array of adjectives
DECLARE adje$[] = { "autumn", "hidden", "bitter", "misty", "silent", "empty", "dry", "dark", "summer", "icy", \
        "delicate", "quiet", "white", "cool", "spring", "winter", "patient", "twilight", "dawn", "crimson", \
        "wispy", "weathered", "blue", "billowing", "broken", "cold", "damp", "falling", "frosty", "green" }
' Create array of nouns
DECLARE noun$[] = { "waterfall", "river", "breeze", "moon", "rain", "wind", "sea", "morning", "snow", "lake", \
        "sunset", "pine", "shadow", "leaf", "dawn", "glitter" }
' make randomized ajdective and noun line from array elements
myline1$ = CONCAT$(adje$[RANDOM(BOUND_STR(adje$))], " ", noun$[RANDOM(BOUND_STR(noun$))])
' show result
PRINT myline1$
' show array dimensions
PRINT BOUND_STR(adje$)
PRINT BOUND_STR(noun$)
If we don't know how many elements are in the arrays adje$[] or noun$[], BOUND_STR(adje$) and BOUND_STR(noun$) will tell us.

You can also do the same with numbers:

Code: Select all

DEF FN BOUND_NUM(x) = SIZEOF(x)/SIZEOF(NUMBER)
' Create array of numbers
DECLARE nums[] = { 1, 2, 3.5, 4, -5, 6, 7, 8, 9, 10, 11, 0 }

PRINT BOUND_NUM(nums)
With kind regards,
vovchik

User avatar
GatorDog
Posts: 138
Joined: Tue 12 Sep 2006, 16:43

#132 Post by GatorDog »

Ok, got it. I didn't pick up on "STRING" being variable type re: SIZEOF(STRING)

Thanks for clarification and code :)

GatorDog

big_bass
Posts: 1740
Joined: Mon 13 Aug 2007, 12:21

#133 Post by big_bass »

Thanks GatorDog and vovchik
for code examples

I wanted to
fix a small part of the bacon2bb code
that adds the grey color to the comments

and using regular expressions
simplifies this little part of the code to reduce it down to
just this idea the fix will follow

Joe

code
http://www.puppy2.org/slaxer/regularexp.html

I use this to convert the bb code to html
http://www.bbcode-to-html.com/

*I will have an option to generate html
had to work out the comment part of the code first



@vovchick this is your work with color
you may want to put all these on a web page some day so
here is a start *notice no problem with word wrapping in html
http://www.puppy2.org/slaxer/vovchik-array.html

User avatar
sunburnt
Posts: 5090
Joined: Wed 08 Jun 2005, 23:11
Location: Arizona, U.S.A.

#134 Post by sunburnt »

So the BaCon docs are not quite right...
Arrays must be declared with fixed dimensions, meaning that it is not possible to determine the dimensions of an array using variables or functions, so during program runtime. The reason for this is that the C compiler needs to know the array dimensions during compile time. Therefore the dimensions of an array must be defined with fixed numbers or with CONST definitions.
### Your code example should be added to BaCon`s doc. section on arrays.

### This also answers my Q about filling an array in one statement.

###> Very Good vovchik.! ... Many thanks for the patient guidance...

Post Reply