Results 1 to 2 of 2

Thread: Commandline Perl and Newlines

  1. #1
    Join Date
    Oct 2006
    Location
    St. Louis
    Beans
    52
    Distro
    Ubuntu 11.04 Natty Narwhal

    Commandline Perl and Newlines

    Trying to get a list of domains from some logs.

    Why does this print the data I want but no line breaks:

    Code:
    cat LOGFILE | perl -ne 'print m!(https?://[^/]+)!'

    And this prints line breaks but only the character “1” (yes, I know it matches...) on each line:

    Code:
    cat LOGFILE | perl -ne 'print m!(https?://[^/]+)!."\n"'
    I can do this but why does the behavior change between the first two?:

    Code:
    cat LOGFILE | perl -ne 'print m!(https?://[^/]+)!; print "\n"'

  2. #2
    Join Date
    Mar 2008
    Beans
    4,715
    Distro
    Ubuntu 9.10 Karmic Koala

    Re: Commandline Perl and Newlines

    When you say
    Code:
    print m!(https?://[^/]+)!
    print can take a list of arguments, so "m!(https?://[^/]+)" is called in an array context.
    So "m!(https?://[^/]+)" returns an array whose elements are all the parenthetical groups with matches. Since your regexp has only one parenthetical group, it returns an array with only one element.

    print then concatenates all the elements in the array.

    In the second command,
    Code:
    print m!(https?://[^/]+)!."\n"
    "m!(https?://[^/]+)!" is concatenated with the string "\n". Only scalars can be concatenated with strings. So "m!(https?://[^/]+)!" is now being called in a scalar context. In a scalar context the match operator returns true (1) if a match has been found, and returns false (0) otherwise.

    You could fix the second command by using a comma (to make a list) instead of a period (concatentation operator):
    Code:
    cat LOGFILE | perl -ne 'print m!(https?://[^/]+)!,"\n"'

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •