Showing entries with tag "Python".

Found 2 entries

Python: Null coallesce on an array

I have a small array in Python, and I need to get the 2nd element of that array, or a default value if it's not present. All the other languages (PHP, Perl, Javascript) I use have a simple null coallescing operator that makes it simple, but not Python. I got tired of writing it out every time to so I wrote a simple wrapper function:

x = [2,4,6]

# Get the 3rd item from x
y = arrayItem(2, x, -1) # 6
# Get the 8th (non-existent) item from x
y = arrayItem(7, x, -1) # -1
# Get an item from an array, or a default value if the array isn't big enough
def arrayItem(needle, haystack, default = None):
    if needle > (len(haystack) - 1):
        return default
    else:
        return haystack[needle]

If there is a better, simpler, built-in way I'm open to hearing it.

Leave A Reply - 1 Reply

Perl: A script that contains valid Perl and Python code

Perl has a cool runtime option named -x that causes Perl to scan a file for the first shebang line with perl in it, and start executing there. This allows you to embed Perl in other files, like text files, or email files.

This got me thinking about embedding a working Perl script in another file. Python allows you to have large multi-line comment blocks using triple quotes """ blocks around your text. Using these comment blocks I was able to embed Perl code inside of a Python script. Effectively you can have a single file that is executable by Perl (with -x) and Python. I wrote up a quick proof-of-concept dual language script.

python dual-perl-python.py
perl -x dual-perl-python.py

Gives varying output:

Hello world from Python v3.8.7
Hello world from Perl v5.30.3
Leave A Reply