(patch for Bash) list comprehension and filtering

Discussion in 'Python' started by William Park, Aug 2, 2004.

  1. William Park

    William Park Guest

    1. Here is shell version of Python filter() for array. Essentially,
    you apply a command on each array element, and extract only those
    elements which it returns success (0). This is specialized form of
    list comprehension where you can contruct an array from another
    array, using some sort of test or filtering.

    Usage is
    arrayfilter [-a var] command array
    where 'command' is a function, shell script, or external executable,
    which takes one argument (ie. the array elements). If 'command'
    return success (0), then print the element; and, if it fails
    (non-zero), then skip the element. If -a option is given, then the
    output will be save into array variable 'var', instead of default
    stdout.

    For example,
    a=(1 a 2 b 3 c)
    func () { [[ $1 == [a-z] ]]; }

    arrayfilter func a --> a b c
    arrayfilter -a b func a --> b[1]=a b[3]=b b[5]=c


    2. More generally, here is shell version of Python list comprehension.
    Idea is to apply some test or command on each array element, and
    collect the outputs as parameter expansion. So, for each element of
    array variable 'var',
    ${var| command }
    will expand to the output of 'command' which takes one argument. If
    'command' returns NULL, then that element is skipped. Usage is very
    similar to other parameter expansion, and both '*' and '@' work as
    expected.

    For example,
    a=(1 a 2 b 3 c)
    func () { [[ $1 == [a-z] ]] && echo ".$1."; }

    func x --> .x.
    ${a[*]| func } --> .a. .b. .d.


    Ref:
    http://freshmeat.net/projects/bashdiff/
    http://home.eol.ca/~parkw/index.html#bash
    help arrayfilter
    help '${var|'

    --
    William Park, Open Geometry Consulting, <>
    Toronto, Ontario, Canada
     
    William Park, Aug 2, 2004
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. William Park

    (patch for Bash) GTK+2 + Bash

    William Park, Jul 11, 2005, in forum: XML
    Replies:
    3
    Views:
    2,317
    William Park
    Jul 14, 2005
  2. William Park

    (patch for Bash) try-block and exception

    William Park, Jul 31, 2004, in forum: Python
    Replies:
    6
    Views:
    409
    William Park
    Aug 2, 2004
  3. Debajit Adhikary
    Replies:
    17
    Views:
    702
    Debajit Adhikary
    Oct 18, 2007
  4. Vedran Furac(
    Replies:
    4
    Views:
    340
    Marc 'BlackJack' Rintsch
    Dec 19, 2008
  5. George Sakkis
    Replies:
    3
    Views:
    382
Loading...

Share This Page