SlideShare uma empresa Scribd logo
1 de 29
Baixar para ler offline
Groovy vs. Perl: можно скриптовать.


    Почему захотелось groovy?


    www.ivis.ru он же www.eastview.com -
    это коллектор периодических изданий.


    Всё сделано на Java, и только скрипты
    обработки данных из газет, журналов
    и новостных лент — на Perl.
                        
Захотелось моноплатформенности.
Groovy понравился, но испугались,
потому что:
1) очень много скриптов
переписывать с Perl-а;
2) год назад Groovy казался слишком
молодой технологией.
Но за год Groovy шагнул с версии 1.5.6
до 1.6.3. А в нём лучше regexp-ы.
                    
Groovy — это
       написанный на Java
       объектно-ориентированный
       скриптовый язык,
       компилируемый в байт-код,
       исполняемый на JVM.


    На Groovy написан Grails -
    RoR-подобный web-фреймворк.
                        
Достоинства Groovy.
Тесная интеграция с Java:
    - прямо в Groovy скриптах можно
писать Java-код, потому что GDK -
это расширение JDK;
- из java-кода можновызывать
код groovy;
- из groovy-кода можно вызывать
код скомпилированных классов java.
                      
Существует 4 способа запускать
groovy, если не счиатать
web-приложения:
а). сохранить скрипт в файле и
запустить из командной строки
>./script.groovy
привет
>cat script groovy
#!/usr/bin/env groovy
println 'привет'
                    
б) скомпилировать в java-класс
и запускать с помощью java
> groovyc script.groovy
                   
> ls *class
script.class
> java ­cp $GROOVY_HOME/embeddable/groovy­all­1.6.2.jar:. script
привет




                                
в) выполнять код groovy с помощью
    groovy shell
    >groovysh
    Groovy Shell (1.6.2, JVM: 1.6.0_07)
    Type 'help' or 'h' for help.
    -------------------------------------
    groovy:000> class ФИ {
    groovy:001> def Фамилия
    groovy:002> def Имя
    groovy:003> def какТебяЗовут(){ quot;Меня зовут ${Имя} ${Фамилия}quot; }
    groovy:004> }
    ===> true
    groovy:000> Дизайнер = new ФИ (Фамилия: quot;Ивановquot;, Имя: quot;Иванquot; )
    ===> ФИ@652110
    groovy:000> Дизайнер.какТебяЗовут()
    ===> Меня зовут Иван Иванов
    groovy:000>


                                     
д) выпонять код в groovyConsole




                     
е) делать всё, что надо, прямо из
командной строки, как в Perl:
inline scripting.
е.1) ключ -e - исполнение кода,
записанного в командной строке:
  > groovy -e quot;println 'Hi, YAPC'quot;
  Hi, YAPC
  > groovy -e quot;println 'Hi, ' + args[0]quot; YAPC
  Hi, YAPC
  > groovy -e quot;println 'Hi, ' + args.join('::') + ' 2009'quot; 
  > YAPC Russia
  Hi, YAPC::Russia 2009           
е.2) обработка каждой строки из
входного потока:
переменная line и ключ -n (вместе с -e)
> cat test2.txt
строка в нижнем регистре

> cat test2.txt | groovy -n -e 'println line.toUpperCase()'
СТРОКА В НИЖНЕМ РЕГИСТРЕ

  > cat test2.txt | groovy -n -e 
  > 'k=0; line.split(/s+/).each{ println quot;${++k} quot; + it; }'
  1 строка
  2в
  3 нижнем
  4 регистре                     
е.3) обработка каждой строки из STDIN
(в переменной line лежит очередная
строка ) и печать обработанных
строк в STDOUT: ключ -p (вместе с -e).
> cat test3.txt
Иваненко
Петренко
Сидоренко

 > cat test3.txt | groovy -p -e 
 '(line =~ /енкоb/).replaceAll(quot;iвquot;)'
 Иванiв
 Петрiв
 Сидорiв                         
е.4) обработка файла «in place'
с созданием резервной копии (.bak)
исходного файла: ключ -i (-p -e).
  > cat test3.txt
  Иваненко
  Петренко
  Сидоренко
  > groovy -p -i .bak -e 
  '(line =~ /енкоb/).replaceAll(quot;iвquot;)' test3.txt
  > cat test3.txt
  Иванiв
  Петрiв
  Сидорiв
  > ls test3*
  test3.txt test3.txt.bak       
Структуры даных (Collections)
   Массивы (Lists) — на основе ArrayList
   Хэши (Maps) — на основе HashMap

Для массивов определено много
разных методов: grep, sort, pop, push,
remove, intersect, disjoint, removeAll,
findAll, isCase, max, min, every, any, join, ...

                        
Массивы
myList = ['a', 'bc', 3]
assert myList.size() == 3
assert myList[1] == 'bc'

assert myList.reverse() == [3, 'bc', 'a']

// из диапазона делаем массив
diap = (1..10).toList()
assert diap[4] == 5

myList.push('u'); myList.push('v'); myList.push('w');
assert myList == ['a', 'bc', 3, 'u','v','w']

assert myList[1..3] == [ 'bc', 3, 'u' ]
assert myList[2, 4] == [3, 'v']

top = myList.pop()
                                 
assert top == 'w'
Массивы (продолжение)
yapc = []

yapc += 'Шитов' // добавляем элемент
assert yapc == ['Шитов']

yapc += ['Капранов', 'Закиров']
assert yapc == ['Шитов', 'Капранов', 'Закиров']

yapc << 'Серёжкин' << 'Mons'
assert yapc == ['Шитов', 'Капранов',
                'Закиров', 'Серёжкин', 'Mons']

assert yapc - ['Капранов', 'Закиров'] ==
                            ['Шитов', 'Серёжкин', 'Mons']

assert yapc*2 == ['Шитов', 'Капранов', 'Закиров',
'Серёжкин', 'Mons',
                              
'Шитов', 'Капранов', 'Закиров', 'Серёжкин', 'Mons']
Массивы (продолжение)
то, что в perl: map
то в groovy: each
> perl -e 'print quot;$_nquot; for map { $_ + 7 } (1,2,3);'
8
9
10

> groovy -e '[1,2,3].each{ println it + 7 }'
8
9
10


                                
Массивы (продолжение)
то, что в perl: split, то и в groovy: split
    > perl -e 'print quot;$_nquot; for split(/, / ,quot;Вася, Петяquot; );'
    Вася
    Петя

    > groovy -e quot;s ='Вася, Петя'; s.split(', ').each{ println it }quot;
    Вася
    Петя




                                     
Массивы (продолжение)
что в perl grep, то и в groovy grep
> perl -e 'print quot;$_nquot; for grep { /шка$/ } qw(шишка ёлка);'
шишка

> groovy -e quot;['шишка', 'ёлка'].grep(~/.*шка$/).each{println it}quot;
шишка


В groovy имеется unique
> groovy -e '[1,1,1,2,2].unique().each{println it}'
1
2


                                 
perl sort и groovy sort похожи
> perl -e 'print quot;$_nquot; for sort {$a <=> $b} (111,10,11,1,2,5);'
1
2
5
10
11
111

> groovy -e '[111,10,11,1,2,5].sort{x,y -> x<=>y}.each{println it}'
1
2
5
10
11
111




                                      
Сортировка массива замыканием
    > cat cards_sorter.groovy
    def cards = ['ace', 'queen', 'jack', 'joker', 'king']

    def cardWeight = ['jack': 10, 'queen':20, 'king':30,
                      'ace':40, 'joker':50 ]

    def compareCards =
       { x, y ->

                  if( cardWeight[x] < cardWeight[y] )
                  return -1
                  else if (cardWeight[x] > cardWeight[y])
                  return 1
                  else
                  return 0
        }
                                    
    cards.sort{ x,y -> compareCards(x, y) }.each{ println it }
Результат сортировки массива
    > groovy cards_sorter.groovy
    jack
    queen
    king
    ace
    joker




                               
Хэши (maps)
def myMap = [x:1, y:2, z:3]
def herMap = [z:3, x:1, y: 2]
def hisMap = [э:3, ю:2, я:3]

assert myMap == herMap
hisMap.putAll(herMap) //добавление одного хэша в другой

assert   hisMap == [э:3, ю:2, я:3, z:3, x:1, y: 2]
assert   hisMap.isEmpty() == false
assert   hisMap.size() == 6
assert   hisMap.containsKey('ю') == true
assert   hisMap.containsValue(1) == true

def toSet(list) { new java.util.HashSet(list) }

assert herMap.keySet() == toSet(['x','y','z'])
assert toSet( herMap.values()  ) == toSet( [1, 2, 3] )
 
Хэши (maps) - продолжение
def myMap = [x:1, y:2, z:3]

assert myMap.any {entry -> entry.value > 2}
assert myMap.every {entry -> entry.key > 'a'}

def mySubMap = myMap.subMap( [ 'x', 'y' ] )
assert mySubMap == [x:1, y:2 ]

def greater_then_1 = myMap.findAll{ elem -> elem.value > 1 }
assert greater_then_1 == [ 'y':2, 'z':3 ]

def f = myMap.find {elem -> elem.value == 1}
assert f.key == 'x'
assert f.value == 1

myMap.remove('x')
assert myMap == [y:2, z:3]
                               
Регулярные выражения в groovy
assert quot;32.99quot; == 'Total Amount: $32.99'.find(/(d+).(d{2})/)

// захват групп с помощью замыкания
def roundedAmount(value) {

  value.find(/(d+).(d{2})/)
 {
      fullMatch, dollars, cents ->
      return dollars.toInteger()
      + ( cents.toInteger() > 50 ? 1 : 0 )
  }

                             }

assert quot;33quot; == roundedAmount('Total Amount: $32.99')
assert quot;44quot; == roundedAmount('I paid $44.28 for it')
                            
Регулярные выражения в groovy
(продолжение)
// чтобы найти все совпадения - findAll
def string = quot;Moe Fine, Howard Fine, and Larry Finequot;
def stooges = string.findAll(/(w+) Fine/)

assert stooges == [quot;Moe Finequot;, quot;Howard Finequot;, quot;Larry Finequot;]

// чтобы захватывать группы — используют запыкания
def string = quot;Moe Fine, Howard Fine, and Larry Finequot;
def firstNames = string.findAll(/(w+) Fine/)
                 {
                 match, firstName -> firstName
                 }

assert firstNames == [quot;Moequot;,  quot;Howardquot;, quot;Larryquot;]
 
Регулярные выражения в groovy
(продолжение)
  foo = 42
  str = '''blah
          #foo#
          blah'''
  re = '''(?xm)       # to enable whitespace and comments
             # # a pound sign
             (w+) # the variable name
             # # another pound sign
      '''
  finder = str =~ re
  found = finder[0]
  out = str.replaceAll(found[0], evaluate(found[1]).toString())
  assert out == '''blah
 
          42                      
          blah'''
Что читать про groovy
            'Groovy in Action', Manning, 2007
            Dierk Koenig, Andrew Glover,
            Paul King, Guillaume Laforge, Jon Skeet



            'Groovy Recipes: Greasing the Wheels of Java'
            Pragmatic Bookshelf, 2008
            Scott Davis




                            
* http://groovy.codehaus.org/ - домашняя страница groovy

* http://voituk.kiev.ua - блог Вадима Войтюка
  «Записки искателей»

* http://pleac.sourceforge.net/pleac_groovy/index.html
  PLEAC - Programming Language Examples Alike Cookbook

* http://blog.alno.name/2008/06/using-groovy/ -
  блог Алексея Носкова

* циклы статей Эндрю Гловера на ibm.com, например:
- 'Практически Groovy:
  Разметка с помощью Groovy Builders'
  http://www.ibm.com/developerworks/ru/library/j-pg04125/

- Практически Groovy : MOP и мини-языки
  http://www.ibm.com/developerworks/ru/library/j-pg09205/
                               
* Про регулярные выражения — blog of Ted Nailed

    'Groovy: Don’t Fear the RegExp'
    http://naleid.com/blog/2008/05/19/dont-fear-the-regexp/

  'Groovy 1.6.1 released with new find and findAll
  regexp methods on String'
  http://naleid.com/blog/2009/04/07/groovy-161-released-
with-new-find-and-findall-regexp-methods-on-string/




                                

Mais conteúdo relacionado

Mais procurados

資料庫期末Project Proposal
資料庫期末Project Proposal資料庫期末Project Proposal
資料庫期末Project ProposalFrank Chang
 
Doublons de compétences : le mal français
Doublons de compétences : le mal françaisDoublons de compétences : le mal français
Doublons de compétences : le mal françaisFondation iFRAP
 
技術トレンディセミナー フレームワークとしてのTrac
技術トレンディセミナー フレームワークとしてのTrac技術トレンディセミナー フレームワークとしてのTrac
技術トレンディセミナー フレームワークとしてのTracterada
 
Aghorastra mantra sadhna vidhi in hindi & sanskrit
Aghorastra mantra sadhna vidhi in hindi & sanskritAghorastra mantra sadhna vidhi in hindi & sanskrit
Aghorastra mantra sadhna vidhi in hindi & sanskritSumit Girdharwal
 
OO Design with C++: 1. Inheritance, part 1
OO Design with C++: 1. Inheritance, part 1OO Design with C++: 1. Inheritance, part 1
OO Design with C++: 1. Inheritance, part 1Dmitry Stillermann
 
企业级搜索引擎Solr交流
企业级搜索引擎Solr交流企业级搜索引擎Solr交流
企业级搜索引擎Solr交流chuan liang
 
SignWriting in an ASCII World
SignWriting in an ASCII WorldSignWriting in an ASCII World
SignWriting in an ASCII WorldStephen Slevinski
 
Friv 4 friv4 Juegos Friv Games Online
Friv 4   friv4  Juegos Friv Games OnlineFriv 4   friv4  Juegos Friv Games Online
Friv 4 friv4 Juegos Friv Games OnlineNguyễn Học
 

Mais procurados (12)

dRuby
dRubydRuby
dRuby
 
Perfect wedding and bridal
Perfect wedding and bridalPerfect wedding and bridal
Perfect wedding and bridal
 
Postgre Sql 8 4
Postgre Sql 8 4Postgre Sql 8 4
Postgre Sql 8 4
 
資料庫期末Project Proposal
資料庫期末Project Proposal資料庫期末Project Proposal
資料庫期末Project Proposal
 
Doublons de compétences : le mal français
Doublons de compétences : le mal françaisDoublons de compétences : le mal français
Doublons de compétences : le mal français
 
技術トレンディセミナー フレームワークとしてのTrac
技術トレンディセミナー フレームワークとしてのTrac技術トレンディセミナー フレームワークとしてのTrac
技術トレンディセミナー フレームワークとしてのTrac
 
Aghorastra mantra sadhna vidhi in hindi & sanskrit
Aghorastra mantra sadhna vidhi in hindi & sanskritAghorastra mantra sadhna vidhi in hindi & sanskrit
Aghorastra mantra sadhna vidhi in hindi & sanskrit
 
Why Ror
Why RorWhy Ror
Why Ror
 
OO Design with C++: 1. Inheritance, part 1
OO Design with C++: 1. Inheritance, part 1OO Design with C++: 1. Inheritance, part 1
OO Design with C++: 1. Inheritance, part 1
 
企业级搜索引擎Solr交流
企业级搜索引擎Solr交流企业级搜索引擎Solr交流
企业级搜索引擎Solr交流
 
SignWriting in an ASCII World
SignWriting in an ASCII WorldSignWriting in an ASCII World
SignWriting in an ASCII World
 
Friv 4 friv4 Juegos Friv Games Online
Friv 4   friv4  Juegos Friv Games OnlineFriv 4   friv4  Juegos Friv Games Online
Friv 4 friv4 Juegos Friv Games Online
 

Destaque

Talent Pipeline Datasheet
Talent Pipeline DatasheetTalent Pipeline Datasheet
Talent Pipeline DatasheetNick Goldstein
 
Summit2012 proposal-sarah maddox
Summit2012 proposal-sarah maddoxSummit2012 proposal-sarah maddox
Summit2012 proposal-sarah maddoxSarah Maddox
 
Koning wilde niet dat Roger Lallemand minister van Staat werd
Koning wilde niet dat Roger Lallemand minister van Staat werdKoning wilde niet dat Roger Lallemand minister van Staat werd
Koning wilde niet dat Roger Lallemand minister van Staat werdThierry Debels
 
LIASA HELIG Publishing Tips for Librarians
LIASA HELIG Publishing Tips for LibrariansLIASA HELIG Publishing Tips for Librarians
LIASA HELIG Publishing Tips for LibrariansHELIGLIASA
 
60 Creative Movie Posters
60 Creative Movie Posters60 Creative Movie Posters
60 Creative Movie PostersDainis Graveris
 
What Did the HR Tech Salesperson Say? SHRM Annual 2014 Presentation
What Did the HR Tech Salesperson Say? SHRM Annual 2014 PresentationWhat Did the HR Tech Salesperson Say? SHRM Annual 2014 Presentation
What Did the HR Tech Salesperson Say? SHRM Annual 2014 PresentationH3 HR Advisors, Inc.
 
Trust Stranger or Boss
Trust Stranger or BossTrust Stranger or Boss
Trust Stranger or BossO.C. Tanner
 
A Peek into Doner's Social Practice
A Peek into Doner's Social PracticeA Peek into Doner's Social Practice
A Peek into Doner's Social PracticeMarcus Collins
 
タイ人オタクが艦これ聖地山を巡った話 第2話 神戸 摩耶
タイ人オタクが艦これ聖地山を巡った話 第2話 神戸 摩耶タイ人オタクが艦これ聖地山を巡った話 第2話 神戸 摩耶
タイ人オタクが艦これ聖地山を巡った話 第2話 神戸 摩耶Matumit Sombunjaroen
 
(Sadn1013 h) kump 22
(Sadn1013 h) kump 22(Sadn1013 h) kump 22
(Sadn1013 h) kump 22sadn1013
 
Performance Recognition
Performance RecognitionPerformance Recognition
Performance RecognitionO.C. Tanner
 
10 Simple Ways to Stay Motivated, always
10 Simple Ways to Stay Motivated, always10 Simple Ways to Stay Motivated, always
10 Simple Ways to Stay Motivated, alwaysRedwan Hossain Shovon
 

Destaque (18)

Iee830
Iee830Iee830
Iee830
 
K+p seminar Telia
K+p seminar TeliaK+p seminar Telia
K+p seminar Telia
 
Take a Stroll in the Bazaar
Take a Stroll in the BazaarTake a Stroll in the Bazaar
Take a Stroll in the Bazaar
 
Talent Pipeline Datasheet
Talent Pipeline DatasheetTalent Pipeline Datasheet
Talent Pipeline Datasheet
 
Summit2012 proposal-sarah maddox
Summit2012 proposal-sarah maddoxSummit2012 proposal-sarah maddox
Summit2012 proposal-sarah maddox
 
Koning wilde niet dat Roger Lallemand minister van Staat werd
Koning wilde niet dat Roger Lallemand minister van Staat werdKoning wilde niet dat Roger Lallemand minister van Staat werd
Koning wilde niet dat Roger Lallemand minister van Staat werd
 
Resume C&I
Resume C&IResume C&I
Resume C&I
 
No credit check loans
No credit check loansNo credit check loans
No credit check loans
 
LIASA HELIG Publishing Tips for Librarians
LIASA HELIG Publishing Tips for LibrariansLIASA HELIG Publishing Tips for Librarians
LIASA HELIG Publishing Tips for Librarians
 
60 Creative Movie Posters
60 Creative Movie Posters60 Creative Movie Posters
60 Creative Movie Posters
 
What Did the HR Tech Salesperson Say? SHRM Annual 2014 Presentation
What Did the HR Tech Salesperson Say? SHRM Annual 2014 PresentationWhat Did the HR Tech Salesperson Say? SHRM Annual 2014 Presentation
What Did the HR Tech Salesperson Say? SHRM Annual 2014 Presentation
 
Trust Stranger or Boss
Trust Stranger or BossTrust Stranger or Boss
Trust Stranger or Boss
 
A Peek into Doner's Social Practice
A Peek into Doner's Social PracticeA Peek into Doner's Social Practice
A Peek into Doner's Social Practice
 
タイ人オタクが艦これ聖地山を巡った話 第2話 神戸 摩耶
タイ人オタクが艦これ聖地山を巡った話 第2話 神戸 摩耶タイ人オタクが艦これ聖地山を巡った話 第2話 神戸 摩耶
タイ人オタクが艦これ聖地山を巡った話 第2話 神戸 摩耶
 
(Sadn1013 h) kump 22
(Sadn1013 h) kump 22(Sadn1013 h) kump 22
(Sadn1013 h) kump 22
 
Performance Recognition
Performance RecognitionPerformance Recognition
Performance Recognition
 
10 Simple Ways to Stay Motivated, always
10 Simple Ways to Stay Motivated, always10 Simple Ways to Stay Motivated, always
10 Simple Ways to Stay Motivated, always
 
Nuevas tecnologias
Nuevas tecnologiasNuevas tecnologias
Nuevas tecnologias
 

Semelhante a Groovy Vs Perl

Упаковка и развертывание программ на perl под debian‎
Упаковка и развертывание программ на perl под debian‎Упаковка и развертывание программ на perl под debian‎
Упаковка и развертывание программ на perl под debian‎mayperl
 
тупицын Ec2 Rootconf2009
тупицын Ec2 Rootconf2009тупицын Ec2 Rootconf2009
тупицын Ec2 Rootconf2009Liudmila Li
 
20080424 Cdb2008 Postgresql News Bartunov
20080424 Cdb2008 Postgresql News Bartunov20080424 Cdb2008 Postgresql News Bartunov
20080424 Cdb2008 Postgresql News BartunovNikolay Samokhvalov
 
とちぎRuby会議01(原)
とちぎRuby会議01(原)とちぎRuby会議01(原)
とちぎRuby会議01(原)Shin-ichiro HARA
 
P2 P Mobile Advertising And Targeting
P2 P Mobile Advertising And TargetingP2 P Mobile Advertising And Targeting
P2 P Mobile Advertising And Targetingguest258f78a
 
Как сделать контрибут в Ruby on Rails
Как сделать контрибут в Ruby on RailsКак сделать контрибут в Ruby on Rails
Как сделать контрибут в Ruby on RailsYaroslav Markin
 
Perl в хэке и хэки в Perl
Perl в хэке и хэки в PerlPerl в хэке и хэки в Perl
Perl в хэке и хэки в Perlmayperl
 
Основы работы с Memcached
Основы работы с MemcachedОсновы работы с Memcached
Основы работы с Memcachedrailsclub
 
Intro To RDBMS And SQL Server 2005 - Svetlin Nakov
Intro To RDBMS And SQL Server 2005 - Svetlin NakovIntro To RDBMS And SQL Server 2005 - Svetlin Nakov
Intro To RDBMS And SQL Server 2005 - Svetlin NakovSvetlin Nakov
 
Защо Ruby on Rails
Защо Ruby on RailsЗащо Ruby on Rails
Защо Ruby on RailsStefan Kanev
 
WindowsユーザのためのはじめてのPerlプログラミング
WindowsユーザのためのはじめてのPerlプログラミングWindowsユーザのためのはじめてのPerlプログラミング
WindowsユーザのためのはじめてのPerlプログラミングYosuke HASEGAWA
 
Что такое ASP.NET MVC?
Что такое ASP.NET MVC?Что такое ASP.NET MVC?
Что такое ASP.NET MVC?Dima Pasko
 
[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And Port[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And PortKeiichi Daiba
 
Erlang with Regexp Perl And Port
Erlang with Regexp Perl And PortErlang with Regexp Perl And Port
Erlang with Regexp Perl And PortKeiichi Daiba
 
Ajax и будущее Java Script
Ajax и будущее Java ScriptAjax и будущее Java Script
Ajax и будущее Java ScriptConstantin Kichinsky
 

Semelhante a Groovy Vs Perl (20)

за Ruby
за Rubyза Ruby
за Ruby
 
Упаковка и развертывание программ на perl под debian‎
Упаковка и развертывание программ на perl под debian‎Упаковка и развертывание программ на perl под debian‎
Упаковка и развертывание программ на perl под debian‎
 
тупицын Ec2 Rootconf2009
тупицын Ec2 Rootconf2009тупицын Ec2 Rootconf2009
тупицын Ec2 Rootconf2009
 
20080424 Cdb2008 Postgresql News Bartunov
20080424 Cdb2008 Postgresql News Bartunov20080424 Cdb2008 Postgresql News Bartunov
20080424 Cdb2008 Postgresql News Bartunov
 
とちぎRuby会議01(原)
とちぎRuby会議01(原)とちぎRuby会議01(原)
とちぎRuby会議01(原)
 
Nop2
Nop2Nop2
Nop2
 
P2 P Mobile Advertising And Targeting
P2 P Mobile Advertising And TargetingP2 P Mobile Advertising And Targeting
P2 P Mobile Advertising And Targeting
 
Как сделать контрибут в Ruby on Rails
Как сделать контрибут в Ruby on RailsКак сделать контрибут в Ruby on Rails
Как сделать контрибут в Ruby on Rails
 
Perl в хэке и хэки в Perl
Perl в хэке и хэки в PerlPerl в хэке и хэки в Perl
Perl в хэке и хэки в Perl
 
Основы работы с Memcached
Основы работы с MemcachedОсновы работы с Memcached
Основы работы с Memcached
 
Intro To RDBMS And SQL Server 2005 - Svetlin Nakov
Intro To RDBMS And SQL Server 2005 - Svetlin NakovIntro To RDBMS And SQL Server 2005 - Svetlin Nakov
Intro To RDBMS And SQL Server 2005 - Svetlin Nakov
 
Защо Ruby on Rails
Защо Ruby on RailsЗащо Ruby on Rails
Защо Ruby on Rails
 
WindowsユーザのためのはじめてのPerlプログラミング
WindowsユーザのためのはじめてのPerlプログラミングWindowsユーザのためのはじめてのPerlプログラミング
WindowsユーザのためのはじめてのPerlプログラミング
 
Что такое ASP.NET MVC?
Что такое ASP.NET MVC?Что такое ASP.NET MVC?
Что такое ASP.NET MVC?
 
Hasql in practice (Russian)
Hasql in practice (Russian)Hasql in practice (Russian)
Hasql in practice (Russian)
 
[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And Port[Erlang LT] Regexp Perl And Port
[Erlang LT] Regexp Perl And Port
 
Erlang with Regexp Perl And Port
Erlang with Regexp Perl And PortErlang with Regexp Perl And Port
Erlang with Regexp Perl And Port
 
Grails Hackday, Spb
Grails Hackday, SpbGrails Hackday, Spb
Grails Hackday, Spb
 
Ajax и будущее Java Script
Ajax и будущее Java ScriptAjax и будущее Java Script
Ajax и будущее Java Script
 
OpenSPARC
OpenSPARCOpenSPARC
OpenSPARC
 

Mais de mayperl

‎Тестирование в проекте REG.RU‎
‎Тестирование в проекте REG.RU‎‎Тестирование в проекте REG.RU‎
‎Тестирование в проекте REG.RU‎mayperl
 
Use Perl like Perl
Use Perl like PerlUse Perl like Perl
Use Perl like Perlmayperl
 
Anyevent
AnyeventAnyevent
Anyeventmayperl
 
Perl + nginx = ♥‎
Perl + nginx = ♥‎Perl + nginx = ♥‎
Perl + nginx = ♥‎mayperl
 
Browser sniffing в 21 веке‎
Browser sniffing в 21 веке‎Browser sniffing в 21 веке‎
Browser sniffing в 21 веке‎mayperl
 
А у нас Perl 6 в production :)
А у нас Perl 6 в production :)А у нас Perl 6 в production :)
А у нас Perl 6 в production :)mayperl
 
Что будет с Перлом?
Что будет с Перлом?Что будет с Перлом?
Что будет с Перлом?mayperl
 
Использование WebMoney в Perl‎
Использование WebMoney в Perl‎Использование WebMoney в Perl‎
Использование WebMoney в Perl‎mayperl
 
Вебклуб Perlgolf.ru
Вебклуб Perlgolf.ruВебклуб Perlgolf.ru
Вебклуб Perlgolf.rumayperl
 
Работа с большими файлами под перлом‎
Работа с большими файлами под перлом‎Работа с большими файлами под перлом‎
Работа с большими файлами под перлом‎mayperl
 
Сравнение работы алгоритмов сортировки, реализованных на Perl
Сравнение работы алгоритмов сортировки, реализованных на PerlСравнение работы алгоритмов сортировки, реализованных на Perl
Сравнение работы алгоритмов сортировки, реализованных на Perlmayperl
 
Курс Perl в УрГУ
Курс Perl в УрГУКурс Perl в УрГУ
Курс Perl в УрГУmayperl
 
Ведение документации в perl6: POD, да не тот !
Ведение документации в perl6: POD, да не тот !Ведение документации в perl6: POD, да не тот !
Ведение документации в perl6: POD, да не тот !mayperl
 
Making Your Own CPAN
Making Your Own CPANMaking Your Own CPAN
Making Your Own CPANmayperl
 
Распределенная обработка потоковых данных
Распределенная обработка потоковых данныхРаспределенная обработка потоковых данных
Распределенная обработка потоковых данныхmayperl
 
Написание DSL в Perl
Написание DSL в PerlНаписание DSL в Perl
Написание DSL в Perlmayperl
 
10.000 вариантов снять квартиру или сам себе POE-риелтор
10.000 вариантов снять квартиру или сам себе POE-риелтор10.000 вариантов снять квартиру или сам себе POE-риелтор
10.000 вариантов снять квартиру или сам себе POE-риелторmayperl
 

Mais de mayperl (17)

‎Тестирование в проекте REG.RU‎
‎Тестирование в проекте REG.RU‎‎Тестирование в проекте REG.RU‎
‎Тестирование в проекте REG.RU‎
 
Use Perl like Perl
Use Perl like PerlUse Perl like Perl
Use Perl like Perl
 
Anyevent
AnyeventAnyevent
Anyevent
 
Perl + nginx = ♥‎
Perl + nginx = ♥‎Perl + nginx = ♥‎
Perl + nginx = ♥‎
 
Browser sniffing в 21 веке‎
Browser sniffing в 21 веке‎Browser sniffing в 21 веке‎
Browser sniffing в 21 веке‎
 
А у нас Perl 6 в production :)
А у нас Perl 6 в production :)А у нас Perl 6 в production :)
А у нас Perl 6 в production :)
 
Что будет с Перлом?
Что будет с Перлом?Что будет с Перлом?
Что будет с Перлом?
 
Использование WebMoney в Perl‎
Использование WebMoney в Perl‎Использование WebMoney в Perl‎
Использование WebMoney в Perl‎
 
Вебклуб Perlgolf.ru
Вебклуб Perlgolf.ruВебклуб Perlgolf.ru
Вебклуб Perlgolf.ru
 
Работа с большими файлами под перлом‎
Работа с большими файлами под перлом‎Работа с большими файлами под перлом‎
Работа с большими файлами под перлом‎
 
Сравнение работы алгоритмов сортировки, реализованных на Perl
Сравнение работы алгоритмов сортировки, реализованных на PerlСравнение работы алгоритмов сортировки, реализованных на Perl
Сравнение работы алгоритмов сортировки, реализованных на Perl
 
Курс Perl в УрГУ
Курс Perl в УрГУКурс Perl в УрГУ
Курс Perl в УрГУ
 
Ведение документации в perl6: POD, да не тот !
Ведение документации в perl6: POD, да не тот !Ведение документации в perl6: POD, да не тот !
Ведение документации в perl6: POD, да не тот !
 
Making Your Own CPAN
Making Your Own CPANMaking Your Own CPAN
Making Your Own CPAN
 
Распределенная обработка потоковых данных
Распределенная обработка потоковых данныхРаспределенная обработка потоковых данных
Распределенная обработка потоковых данных
 
Написание DSL в Perl
Написание DSL в PerlНаписание DSL в Perl
Написание DSL в Perl
 
10.000 вариантов снять квартиру или сам себе POE-риелтор
10.000 вариантов снять квартиру или сам себе POE-риелтор10.000 вариантов снять квартиру или сам себе POE-риелтор
10.000 вариантов снять квартиру или сам себе POE-риелтор
 

Último

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 

Último (20)

Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 

Groovy Vs Perl

  • 1. Groovy vs. Perl: можно скриптовать. Почему захотелось groovy? www.ivis.ru он же www.eastview.com - это коллектор периодических изданий. Всё сделано на Java, и только скрипты обработки данных из газет, журналов и новостных лент — на Perl.    
  • 2. Захотелось моноплатформенности. Groovy понравился, но испугались, потому что: 1) очень много скриптов переписывать с Perl-а; 2) год назад Groovy казался слишком молодой технологией. Но за год Groovy шагнул с версии 1.5.6 до 1.6.3. А в нём лучше regexp-ы.    
  • 3. Groovy — это  написанный на Java  объектно-ориентированный  скриптовый язык,  компилируемый в байт-код,  исполняемый на JVM. На Groovy написан Grails -   RoR-подобный web-фреймворк.  
  • 4. Достоинства Groovy. Тесная интеграция с Java: - прямо в Groovy скриптах можно писать Java-код, потому что GDK - это расширение JDK; - из java-кода можновызывать код groovy; - из groovy-кода можно вызывать код скомпилированных классов java.    
  • 5. Существует 4 способа запускать groovy, если не счиатать web-приложения: а). сохранить скрипт в файле и запустить из командной строки >./script.groovy привет >cat script groovy #!/usr/bin/env groovy println 'привет'    
  • 6. б) скомпилировать в java-класс и запускать с помощью java > groovyc script.groovy                 > ls *class script.class > java ­cp $GROOVY_HOME/embeddable/groovy­all­1.6.2.jar:. script привет    
  • 7. в) выполнять код groovy с помощью groovy shell >groovysh Groovy Shell (1.6.2, JVM: 1.6.0_07) Type 'help' or 'h' for help. ------------------------------------- groovy:000> class ФИ { groovy:001> def Фамилия groovy:002> def Имя groovy:003> def какТебяЗовут(){ quot;Меня зовут ${Имя} ${Фамилия}quot; } groovy:004> } ===> true groovy:000> Дизайнер = new ФИ (Фамилия: quot;Ивановquot;, Имя: quot;Иванquot; ) ===> ФИ@652110 groovy:000> Дизайнер.какТебяЗовут() ===> Меня зовут Иван Иванов groovy:000>    
  • 8. д) выпонять код в groovyConsole    
  • 9. е) делать всё, что надо, прямо из командной строки, как в Perl: inline scripting. е.1) ключ -e - исполнение кода, записанного в командной строке: > groovy -e quot;println 'Hi, YAPC'quot; Hi, YAPC > groovy -e quot;println 'Hi, ' + args[0]quot; YAPC Hi, YAPC > groovy -e quot;println 'Hi, ' + args.join('::') + ' 2009'quot; > YAPC Russia   Hi, YAPC::Russia 2009  
  • 10. е.2) обработка каждой строки из входного потока: переменная line и ключ -n (вместе с -e) > cat test2.txt строка в нижнем регистре > cat test2.txt | groovy -n -e 'println line.toUpperCase()' СТРОКА В НИЖНЕМ РЕГИСТРЕ > cat test2.txt | groovy -n -e > 'k=0; line.split(/s+/).each{ println quot;${++k} quot; + it; }' 1 строка 2в 3 нижнем   4 регистре  
  • 11. е.3) обработка каждой строки из STDIN (в переменной line лежит очередная строка ) и печать обработанных строк в STDOUT: ключ -p (вместе с -e). > cat test3.txt Иваненко Петренко Сидоренко > cat test3.txt | groovy -p -e '(line =~ /енкоb/).replaceAll(quot;iвquot;)' Иванiв Петрiв  Сидорiв  
  • 12. е.4) обработка файла «in place' с созданием резервной копии (.bak) исходного файла: ключ -i (-p -e). > cat test3.txt Иваненко Петренко Сидоренко > groovy -p -i .bak -e '(line =~ /енкоb/).replaceAll(quot;iвquot;)' test3.txt > cat test3.txt Иванiв Петрiв Сидорiв > ls test3*   test3.txt test3.txt.bak  
  • 13. Структуры даных (Collections)  Массивы (Lists) — на основе ArrayList  Хэши (Maps) — на основе HashMap Для массивов определено много разных методов: grep, sort, pop, push, remove, intersect, disjoint, removeAll, findAll, isCase, max, min, every, any, join, ...    
  • 14. Массивы myList = ['a', 'bc', 3] assert myList.size() == 3 assert myList[1] == 'bc' assert myList.reverse() == [3, 'bc', 'a'] // из диапазона делаем массив diap = (1..10).toList() assert diap[4] == 5 myList.push('u'); myList.push('v'); myList.push('w'); assert myList == ['a', 'bc', 3, 'u','v','w'] assert myList[1..3] == [ 'bc', 3, 'u' ] assert myList[2, 4] == [3, 'v'] top = myList.pop()     assert top == 'w'
  • 15. Массивы (продолжение) yapc = [] yapc += 'Шитов' // добавляем элемент assert yapc == ['Шитов'] yapc += ['Капранов', 'Закиров'] assert yapc == ['Шитов', 'Капранов', 'Закиров'] yapc << 'Серёжкин' << 'Mons' assert yapc == ['Шитов', 'Капранов', 'Закиров', 'Серёжкин', 'Mons'] assert yapc - ['Капранов', 'Закиров'] == ['Шитов', 'Серёжкин', 'Mons'] assert yapc*2 == ['Шитов', 'Капранов', 'Закиров', 'Серёжкин', 'Mons',     'Шитов', 'Капранов', 'Закиров', 'Серёжкин', 'Mons']
  • 16. Массивы (продолжение) то, что в perl: map то в groovy: each > perl -e 'print quot;$_nquot; for map { $_ + 7 } (1,2,3);' 8 9 10 > groovy -e '[1,2,3].each{ println it + 7 }' 8 9 10    
  • 17. Массивы (продолжение) то, что в perl: split, то и в groovy: split > perl -e 'print quot;$_nquot; for split(/, / ,quot;Вася, Петяquot; );' Вася Петя > groovy -e quot;s ='Вася, Петя'; s.split(', ').each{ println it }quot; Вася Петя    
  • 18. Массивы (продолжение) что в perl grep, то и в groovy grep > perl -e 'print quot;$_nquot; for grep { /шка$/ } qw(шишка ёлка);' шишка > groovy -e quot;['шишка', 'ёлка'].grep(~/.*шка$/).each{println it}quot; шишка В groovy имеется unique > groovy -e '[1,1,1,2,2].unique().each{println it}' 1 2    
  • 19. perl sort и groovy sort похожи > perl -e 'print quot;$_nquot; for sort {$a <=> $b} (111,10,11,1,2,5);' 1 2 5 10 11 111 > groovy -e '[111,10,11,1,2,5].sort{x,y -> x<=>y}.each{println it}' 1 2 5 10 11 111    
  • 20. Сортировка массива замыканием > cat cards_sorter.groovy def cards = ['ace', 'queen', 'jack', 'joker', 'king'] def cardWeight = ['jack': 10, 'queen':20, 'king':30, 'ace':40, 'joker':50 ] def compareCards = { x, y -> if( cardWeight[x] < cardWeight[y] ) return -1 else if (cardWeight[x] > cardWeight[y]) return 1 else return 0 }     cards.sort{ x,y -> compareCards(x, y) }.each{ println it }
  • 21. Результат сортировки массива > groovy cards_sorter.groovy jack queen king ace joker    
  • 22. Хэши (maps) def myMap = [x:1, y:2, z:3] def herMap = [z:3, x:1, y: 2] def hisMap = [э:3, ю:2, я:3] assert myMap == herMap hisMap.putAll(herMap) //добавление одного хэша в другой assert hisMap == [э:3, ю:2, я:3, z:3, x:1, y: 2] assert hisMap.isEmpty() == false assert hisMap.size() == 6 assert hisMap.containsKey('ю') == true assert hisMap.containsValue(1) == true def toSet(list) { new java.util.HashSet(list) } assert herMap.keySet() == toSet(['x','y','z']) assert toSet( herMap.values()  ) == toSet( [1, 2, 3] )  
  • 23. Хэши (maps) - продолжение def myMap = [x:1, y:2, z:3] assert myMap.any {entry -> entry.value > 2} assert myMap.every {entry -> entry.key > 'a'} def mySubMap = myMap.subMap( [ 'x', 'y' ] ) assert mySubMap == [x:1, y:2 ] def greater_then_1 = myMap.findAll{ elem -> elem.value > 1 } assert greater_then_1 == [ 'y':2, 'z':3 ] def f = myMap.find {elem -> elem.value == 1} assert f.key == 'x' assert f.value == 1 myMap.remove('x') assert myMap == [y:2, z:3]    
  • 24. Регулярные выражения в groovy assert quot;32.99quot; == 'Total Amount: $32.99'.find(/(d+).(d{2})/) // захват групп с помощью замыкания def roundedAmount(value) { value.find(/(d+).(d{2})/) { fullMatch, dollars, cents -> return dollars.toInteger() + ( cents.toInteger() > 50 ? 1 : 0 ) } } assert quot;33quot; == roundedAmount('Total Amount: $32.99') assert quot;44quot; == roundedAmount('I paid $44.28 for it')    
  • 25. Регулярные выражения в groovy (продолжение) // чтобы найти все совпадения - findAll def string = quot;Moe Fine, Howard Fine, and Larry Finequot; def stooges = string.findAll(/(w+) Fine/) assert stooges == [quot;Moe Finequot;, quot;Howard Finequot;, quot;Larry Finequot;] // чтобы захватывать группы — используют запыкания def string = quot;Moe Fine, Howard Fine, and Larry Finequot; def firstNames = string.findAll(/(w+) Fine/) { match, firstName -> firstName } assert firstNames == [quot;Moequot;,  quot;Howardquot;, quot;Larryquot;]  
  • 26. Регулярные выражения в groovy (продолжение) foo = 42 str = '''blah #foo# blah''' re = '''(?xm) # to enable whitespace and comments # # a pound sign (w+) # the variable name # # another pound sign ''' finder = str =~ re found = finder[0] out = str.replaceAll(found[0], evaluate(found[1]).toString()) assert out == '''blah   42   blah'''
  • 27. Что читать про groovy 'Groovy in Action', Manning, 2007 Dierk Koenig, Andrew Glover, Paul King, Guillaume Laforge, Jon Skeet 'Groovy Recipes: Greasing the Wheels of Java' Pragmatic Bookshelf, 2008 Scott Davis    
  • 28. * http://groovy.codehaus.org/ - домашняя страница groovy * http://voituk.kiev.ua - блог Вадима Войтюка «Записки искателей» * http://pleac.sourceforge.net/pleac_groovy/index.html PLEAC - Programming Language Examples Alike Cookbook * http://blog.alno.name/2008/06/using-groovy/ - блог Алексея Носкова * циклы статей Эндрю Гловера на ibm.com, например: - 'Практически Groovy: Разметка с помощью Groovy Builders' http://www.ibm.com/developerworks/ru/library/j-pg04125/ - Практически Groovy : MOP и мини-языки http://www.ibm.com/developerworks/ru/library/j-pg09205/    
  • 29. * Про регулярные выражения — blog of Ted Nailed 'Groovy: Don’t Fear the RegExp' http://naleid.com/blog/2008/05/19/dont-fear-the-regexp/ 'Groovy 1.6.1 released with new find and findAll regexp methods on String' http://naleid.com/blog/2009/04/07/groovy-161-released- with-new-find-and-findall-regexp-methods-on-string/